tags:

views:

921

answers:

0

hello,

following is my code for application which takes data from user.displays it in a list. what i am trying to do is if user clicks delete button specified list entry should be deleted. but my index is not returning properly. please help me i am trying it for last two days.

import net.rim.device.api.ui.; import net.rim.device.api.ui.component.; import net.rim.device.api.ui.container.; import net.rim.device.api.system.; import net.rim.device.api.util.; import java.util.;

//import MusicStores.StoreInfo;

// An application which stores the users data persistently and displays the data in a grid layout // on the next screen. it also gives a search option.

public class Display extends UiApplication {

/*declaring Strings to store the data of the user*/

String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
String getCompany;

/*declaring text fields for user input*/
private AutoTextEditField firstName;

private AutoTextEditField lastName;
private AutoTextEditField company;

private EmailAddressEditField email;

/*declaring choice field for user input*/

private ObjectChoiceField gender;

/*declaring check box field for user input*/
private CheckboxField status;

//Declaring button fields
private ButtonField save;
private ButtonField close;
private ButtonField List;
private ButtonField search;

/*declaring vector*/
private static Vector _data;

/*declaring persistent object*/
private static PersistentObject store;

/*creating an entry point*/
public static void main(String[] args) 
{

 Display obj = new Display();
 obj.enterEventDispatcher();



}

/*creating default constructor*/
public Display() 
{

 /*Creating an object of the main screen class to use its functionalities*/
 MainScreen mainScreen = new MainScreen();

 //setting title of the main screen
 mainScreen.setTitle(new LabelField("Enter Your Data"));

 //creating text fields for user input
 firstName = new AutoTextEditField("First Name: ", "");
 lastName= new AutoTextEditField("Last Name: ", "");
 email= new EmailAddressEditField("Email:: ", "");
 company = new AutoTextEditField("Company: ", "");

 //creating choice field for user input
 String [] items = {"Male","Female"};
 gender= new ObjectChoiceField("Gender",items);

 //creating Check box field
 status = new CheckboxField("Active",true);

 //creating Button fields and adding functionality using listeners

 // A button that saves the the user data persistently when it is clicked
 save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
 save.setChangeListener(new FieldChangeListener()
 {
  public void fieldChanged(Field field, int context)
  {
   save();

  }
 });

 // a button which closes the entire application when clicked
 close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
 close.setChangeListener(new FieldChangeListener()
 {
  public void fieldChanged(Field field, int context)
  {
   onClose();
  }
 });

 // A button that shows the List of all Data being stored persistently
 List = new ButtonField("List",ButtonField.CONSUME_CLICK);
 List.setChangeListener(new FieldChangeListener()
 {
  public void fieldChanged(Field field, int context){
   // pushing the next screen

   pushScreen(new ListScreen());



  }
 });

 search = new ButtonField("Search",ButtonField.CONSUME_CLICK);
 search.setChangeListener(new FieldChangeListener()
 {
  public void fieldChanged(Field field, int context)
  {
   pushScreen(new SearchScreen());
  }
 });
 //adding the input fields to the main screen
 mainScreen.add(firstName);
 mainScreen.add(lastName);
 mainScreen.add(email);
 mainScreen.add(company);
 mainScreen.add(gender);
 mainScreen.add(status);

 // Addning horizontal field manager
 HorizontalFieldManager horizontal = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);

 //adding buttons to the main screen in Horizontal field manager

 horizontal.add(close);
 horizontal.add(save);
 horizontal.add(List);
 horizontal.add(search);

 //Adding the horizontal field manger to the screen
 mainScreen.add(horizontal);

 //adding menu items

 mainScreen.addMenuItem(saveItem);
 mainScreen.addMenuItem(getItem);
 mainScreen.addMenuItem(Deleteall);

 //pushing the main screen
 pushScreen(mainScreen);
}
private MenuItem Deleteall = new MenuItem("Delete all",110,10)
{
 public void run()
 {
  int response = Dialog.ask(Dialog.D_YES_NO,"Are u sure u want to delete entire Database");
  if(Dialog.YES == response){
  PersistentStore.destroyPersistentObject(0xdec6a67096f833cL);
  Dialog.alert("Closing Application");
  onClose();
  }
  else
   Dialog.inform("Thank God");
 }
};

//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10) {

 public void run() 
 {
  //Calling save method
  save();
 }

}; //adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11) { //running thread for this menu item public void run() {

  //synchronizing thread
  synchronized (store) 
  {
   //getting contents of the persistent object

   _data = (Vector) store.getContents();
   try{

    for (int i = _data.size()-1; i >-1; i--) 
    {

     StoreInfo info = (StoreInfo)_data.elementAt(i);
     //checking for empty object
     if (!_data.isEmpty()) 
     {
     //if not empty
     //create a new object of Store Info class






     //storing information retrieved in strings
     getFirstName = (info.getElement(StoreInfo.NAME));
     getLastName  = (info.getElement(StoreInfo.LastNAME));
     getEmail   = (info.getElement(StoreInfo.EMail));
     getGender   =  (info.getElement(StoreInfo.GenDer));
     getStatus  = (info.getElement(StoreInfo.setStatus));
     getCompany  = (info.getElement(StoreInfo.setCompany));
      //calling the show method
     show();
     }

    }
   }
   catch(Exception e){}
  } 
 }

}; public void save() {

//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.setCompany, company.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
 info.setElement(StoreInfo.setStatus, "Active");
else
 info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store) 
{

 store.setContents(_data);
 store.commit();



}
//resetting the input fields

Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
company.setText(null);
gender.setSelectedIndex("Male");
status.setChecked(true);

} //coding for persistent store static {

store = PersistentStore.getPersistentObject(0xdec6a67096f833cL); synchronized (store) { if (store.getContents() == null) { store.setContents(new Vector()); store.commit(); } } _data = new Vector(); _data = (Vector) store.getContents();

} //new class store info implementing persistable private static final class StoreInfo implements Persistable { //declaring variables private Vector _elements; public static final int NAME = 0; public static final int LastNAME = 1; public static final int EMail= 2; public static final int GenDer = 3; public static final int setStatus = 4; public static final int setCompany = 5; public StoreInfo() { _elements = new Vector(6); for (int i = 0; i < _elements.capacity(); ++i) { _elements.addElement(new String("")); } }

public String getElement(int id) 
{
 return (String) _elements.elementAt(id);
}
public void setElement(int id, String value) 
{
 _elements.setElementAt(value, id);
}

} //details for show method public void show() { Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus); } public void list() {

Dialog.alert("haha");

}

//creating save method

//overriding onClose method

public boolean onClose() {

System.exit(0);
return true;

}

class ListScreen extends MainScreen {

 String firstUserName;
 String lastUserName;
 String userEmail;
 String userGender;
 String userStatus;
 String userCompany;
 String listt;
 private AutoTextEditField  userFirstName;
 private AutoTextEditField  userLastName;
 private EmailAddressEditField  userMail;
 private ObjectChoiceField  usersGender;
 private CheckboxField usersStatus; 
 private ButtonField btnBack;
 private Manager mGrid;
 ButtonField btnDelete;
 LabelField lblData;
 int getIndex;
 private ListField list;

 final class MyListField implements ListFieldCallback{
   private Vector listElements = new Vector();


  public void drawListRow(ListField list, Graphics g, int index,
    int y, int w) {
   String text = (String)listElements.elementAt(index);
    g.drawText(text, 0, y, 0, w);


  }

  public Object get(ListField arg0, int index) {
   return listElements.elementAt(index);


  }

  public int getPreferredWidth(ListField listField) {
   return Graphics.getScreenWidth();

  }

  public int indexOfList(ListField listField, String prefix, int start) {
   return listElements.indexOf(prefix, start);

  }
  public void insert(String toInsert, int index) {
   listElements.addElement(toInsert);
   }
   public void erase() {
   listElements.removeAllElements();
   }



  }

public ListScreen()
{
 SeparatorField sps = new SeparatorField();
 HorizontalFieldManager hr = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER|HorizontalFieldManager.HORIZONTAL_SCROLLBAR);
 VerticalFieldManager vr = new VerticalFieldManager();
 setTitle(new LabelField("List of All Data"));
 myList();
 btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
 btnBack.setChangeListener(new FieldChangeListener()
 {
  public void fieldChanged(Field field,int context)
  {
   UiApplication.getUiApplication().popScreen(getScreen());
  }
 });

 hr.add(btnBack);



 add(hr);
 add(sps);

}
public void myList()
{
 _data = (Vector) store.getContents();
 try
 {
  for (int i = _data.size()-1; i >-1; i--) 
   {

    StoreInfo info = (StoreInfo)_data.elementAt(i);
    //checking for empty object
    if (!_data.isEmpty()) 
     {
      //if not empty
      //create a new object of Store Info class






      //storing information retrieved in strings
      //StoreInfo info = (StoreInfo)_data.lastElement();
      firstUserName = (info.getElement(StoreInfo.NAME));
      lastUserName  = (info.getElement(StoreInfo.LastNAME));
      userEmail   = (info.getElement(StoreInfo.EMail));
      userGender   =  (info.getElement(StoreInfo.GenDer));
      userStatus  = (info.getElement(StoreInfo.setStatus));
      userCompany     = (info.getElement(StoreInfo.setCompany));

  list = new ListField();
  MyListField myList  = new MyListField();
  list.setCallback(myList);
  String data = firstUserName + " "+ lastUserName +"  "+ userEmail+ "  " +userCompany+" "+ userGender  + " " +userStatus ;

  list.insert(0);
  myList.insert(data, 0);
  add(list);

  btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
  btnDelete.setChangeListener(new FieldChangeListener()
  {
   public void fieldChanged(Field field, int context)
   {

     //Delete(list.getIndex());
     Delete(list.getSelectedIndex());
    }
  });
  add(btnDelete);
  SeparatorField sp = new SeparatorField();

  add(sp);

  }
   }
 }
  catch(Exception e){}


}
public void get(ListField list, int index)
{
 Dialog.alert("me at "+index);
}
public void Delete(int index)
{
 //Dialog.alert("Index"+index);
_data.removeElementAt(index);
UiApplication.getUiApplication().popScreen(getScreen());
}

public void gridList()

{

if (null != mGrid && null != mGrid.getManager())
    mGrid.getManager().delete(mGrid);

int colWidth = net.rim.device.api.system.Display.getWidth() / 4; mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth, colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR); mGrid.add(new NullField(FOCUSABLE)); mGrid.add(new LabelField("Name")); mGrid.add(new LabelField("E-Mail")); mGrid.add(new LabelField("Gender")); mGrid.add(new LabelField("Active")); add(mGrid); _data = (Vector) store.getContents(); try { int sn = 0; for (int i = _data.size() - 1; i > -1; i--, sn++) {

            StoreInfo info = (StoreInfo) _data.elementAt(i);
            // checking for empty object
            if (!_data.isEmpty()) {
                    // if not empty
                    // create a new object of Store Info class

                    // storing information retrieved in strings
                    firstUserName = (info.getElement(StoreInfo.NAME));
                    lastUserName = (info.getElement(StoreInfo.LastNAME));
                    userEmail = (info.getElement(StoreInfo.EMail));
                    userGender = (info.getElement(StoreInfo.GenDer));
                    userStatus = (info.getElement(StoreInfo.setStatus));

                    // calling the listAll method
                    mGrid.add(new NullField(FOCUSABLE));
                    mGrid.add(new LabelField(firstUserName + " "
                                    + lastUserName));
                    mGrid.add(new LabelField(userEmail));
                    mGrid.add(new LabelField(userGender));
                    mGrid.add(new LabelField(userStatus));

            }

    }

} catch (Exception e) { } SeparatorField sps = new SeparatorField(); add(sps);

/*
_data = (Vector) store.getContents();
try{
 int sn=0;
 for (int i = _data.size()-1; i >-1; i--,sn++) 
 {

  StoreInfo info = (StoreInfo)_data.elementAt(i);
  //checking for empty object
  if (!_data.isEmpty()) 
  {
  //if not empty
  //create a new object of Store Info class






  //storing information retrieved in strings
   firstUserName = (info.getElement(StoreInfo.NAME));
   lastUserName = (info.getElement(StoreInfo.LastNAME));
   userEmail  = (info.getElement(StoreInfo.EMail));
   userGender   =  (info.getElement(StoreInfo.GenDer));
   userStatus  = (info.getElement(StoreInfo.setStatus));

   //calling the listAll method
  listAll();
  }

 }
}
catch(Exception e){} */

}
/*public void listAll()
{
 //Manger gridField = new GridFieldManager(2, 0);

 SeparatorField sp = new SeparatorField();
 SeparatorField sps = new SeparatorField();
 HorizontalFieldManager hrs = new HorizontalFieldManager(HorizontalFieldManager.HORIZONTAL_SCROLL);
 hrs.add(new RichTextField(""+firstUserName+" "+lastUserName+" | "+userEmail+" | "+userGender+" | "+userStatus));
 //add(new RichTextField("Email: "+userEmail));
 //add(new RichTextField("Gender: "+userGender));
 //add(new RichTextField("Status: "+userStatus));
 //SeparatorField sp = new SeparatorField();
 add(hrs);
 add(sp);
 add(sps);

}*/

public boolean onClose()
{
 System.exit(0);
 return true;
}

} class SearchScreen extends MainScreen { private ButtonField btnFirstName; private ButtonField btnLastName; private ButtonField btnSearch; private ButtonField btnEmail; private SeparatorField sp; String userName; HorizontalFieldManager hr = new HorizontalFieldManager();

public AutoTextEditField searchField;

 public SearchScreen()
 {


  sp = new SeparatorField();
  setTitle(new LabelField("your Search Options"));
  add(new RichTextField("Search by : "));

  btnFirstName = new ButtonField("First Name",ButtonField.CONSUME_CLICK);
  hr.add(btnFirstName);

  btnFirstName.setChangeListener(new FieldChangeListener()
    {
     public void fieldChanged(Field field, int context) 
     {
      //HorizontalFieldManager hrs = new HorizontalFieldManager();
     searchField = new AutoTextEditField("First Name: ","ali");
     add(searchField);
     btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
     btnSearch.setChangeListener(new FieldChangeListener()
     {
      public void fieldChanged(Field field, int context)
      {
       //Dialog.alert(searchField.getText());
       pushScreen(new FirstnameScreen(searchField.getText()));
       //FirstnameScreen obj = new FirstnameScreen();
       //obj.name= searchField.getText();

      }
     });
     add(btnSearch);
     //hrs.add(sp);
    }
    });


  btnLastName = new ButtonField("Last Name",ButtonField.CONSUME_CLICK);
  hr.add(btnLastName);
  btnLastName.setChangeListener(new FieldChangeListener()
  {
   public void fieldChanged(Field field, int Context)
   {
    searchField = new AutoTextEditField("Last Name: ","");
    add(searchField);
    btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
    btnSearch.setChangeListener(new FieldChangeListener()
    {
     public void fieldChanged(Field field, int context)
     {
      //Dialog.alert(searchField.getText());
      pushScreen(new LastnameScreen(searchField.getText()));
      //FirstnameScreen obj = new FirstnameScreen();
      //obj.name= searchField.getText();

     }
    });
    add(btnSearch);

   }
  });
  btnEmail = new ButtonField("Email",ButtonField.CONSUME_CLICK);
  hr.add(btnEmail);
  btnEmail.setChangeListener(new FieldChangeListener()
  {
   public void fieldChanged(Field field, int Context)
   {
    searchField = new AutoTextEditField("Email: ","");
    add(searchField);
    btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
    btnSearch.setChangeListener(new FieldChangeListener()
    {
     public void fieldChanged(Field field, int context)
     {
      //Dialog.alert(searchField.getText());
      pushScreen(new EmailScreen(searchField.getText()));
      //FirstnameScreen obj = new FirstnameScreen();
      //obj.name= searchField.getText();

     }
    });
    add(btnSearch);
   }
  });   
  add(hr);

 }
 void myShow()
 {
  Dialog.alert(searchField.getText());
 }

} class FirstnameScreen extends MainScreen { String userName; private Manager mGrid; String firstUserName; String lastUserName; String userEmail; String userGender; String userStatus; ButtonField btnBack; Font font;

 public FirstnameScreen(String name)
 {
  setTitle(new LabelField("your Search Results"));
  add(new RichTextField("Search results for"+name));
  userName = name; 
  searchFirstName();
  btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
  btnBack.setChangeListener(new FieldChangeListener()
  {
   public void fieldChanged(Field field, int context)
   {
    UiApplication.getUiApplication().popScreen(getScreen());
   }
  });
  add(btnBack);


 }


 public void searchFirstName()
 {

  ButtonField btnDelete;
  if (null != mGrid && null != mGrid.getManager())
         mGrid.getManager().delete(mGrid);
 int colWidth = net.rim.device.api.system.Display.getWidth() / 4; 
 mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
                 colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
 mGrid.add(new NullField(FOCUSABLE));
 mGrid.add(new LabelField("Name"));
 mGrid.add(new LabelField("E-Mail"));
 mGrid.add(new LabelField("Gender"));
 mGrid.add(new LabelField("Active"));
 //mGrid.add(new ButtonField("Delete"));

 //SeparatorField sps = new SeparatorField();
 //mGrid.add(sps);
 add(mGrid);
 _data = (Vector) store.getContents();
 try {

         for (int i = _data.size() - 1; i > -1; i--) {

                 StoreInfo info = (StoreInfo) _data.elementAt(i);
                 // checking for empty object
                 if (!_data.isEmpty()) {

                  firstUserName = (info.getElement(StoreInfo.NAME));
                  if(firstUserName.equalsIgnoreCase(userName))
                  {
                         // if not empty
                         // create a new object of Store Info class

                         // stored information retrieved in strings

                         lastUserName = (info.getElement(StoreInfo.LastNAME));
                         userEmail = (info.getElement(StoreInfo.EMail));
                         userGender = (info.getElement(StoreInfo.GenDer));
                         userStatus = (info.getElement(StoreInfo.setStatus));
                         final int sn = i;

                         // calling the listAll method
                         mGrid.add(new NullField(FOCUSABLE));
                         mGrid.add(new LabelField(firstUserName + " "
                                         + lastUserName));
                         mGrid.add(new LabelField(userEmail));
                         mGrid.add(new LabelField(userGender));
                         mGrid.add(new LabelField(userStatus));
                         btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
                         btnDelete.setChangeListener(new FieldChangeListener()
                         {
                          public void fieldChanged(Field field, int context)
                          {
                           _data.removeElementAt(sn);
                          }
                         });
                         add(btnDelete);

                        // SeparatorField sps1 = new SeparatorField();
                   //mGrid.add(sps1);




                  }


                 }

         }
 } catch (Exception e) {
 }


 }

}

class LastnameScreen extends MainScreen { public LastnameScreen(String name) { setTitle(new LabelField("your Search Results")); } } class EmailScreen extends MainScreen { public EmailScreen(String mail) { setTitle(new LabelField("your Search Results")); }

} }

related questions