Как мне посчитать все количество записей в RecordStore

У меня есть приложение LWUIT, которое должно отображать количество записей в списке LWUIT.

Чтобы получить все записи, я использую метод под названием getRecordData() который возвращает все записи в виде массива String, он работает нормально.

Но как мне посчитать количество этих записей?

import java.util.*;
import com.sun.lwuit.events.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.plaf.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms .*;
public class number_of_records extends MIDlet {
    private RecordStore recordStore;
    // Refresh2( ) method for getting the time now
    public String Refresh2()
    {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        Date myDate = new Date();
        calendar.setTime(myDate);
        StringBuffer time = new StringBuffer();
        time.append(calendar.get(java.util.Calendar.HOUR_OF_DAY)).append(':');
        time.append(calendar.get(java.util.Calendar.MINUTE)) ;
        // time.append(calendar.get(java.util.Calendar.SECOND));
        String tt = time.toString();
        return tt;
    }
    // return all records of recordStore RecordStore
    public String [] getRecordData( )
    {
        String[] str = null;
        int counter = 0;
        try
        {
            RecordEnumeration enumeration = recordStore.enumerateRecords(null, null, false);
            str = new String[recordStore.getNumRecords()];
            while(enumeration.hasNextElement())
            {
                try
                {
                    str[counter] = (new String(enumeration.nextRecord()));
                    counter ++;
                }
                catch(javax.microedition.rms.RecordStoreException e)
                {
                }
            }
        }
        catch(javax.microedition.rms.RecordStoreNotOpenException e)
        {
        }
        catch(java.lang.NullPointerException n)
        {
        }
        return str;
    }
    public void startApp()
    {
        com.sun.lwuit.Display.init(this);
        final Button addition = new Button("add a goal");
        final com.sun.lwuit.TextField tf = new com.sun.lwuit.TextField();
        final com.sun.lwuit.List mylist = new com.sun.lwuit.List();
        final Button All = new Button("All Goals");
        final com.sun.lwuit.Form ff = new com.sun.lwuit.Form();
        final com.sun.lwuit.Form g = new com.sun.lwuit.Form();
        ff.getStyle().setBgColor(0X99CCFF);
        All.getStyle().setBgColor(0X0066CC);
        Style g_style5 = g.getSelectedStyle() ;
        g.addComponent(tf);
        g.addComponent(addition);
        addition.getStyle().setBgColor(0X0066CC);
        g.addComponent(All);
        g.getStyle().setBgColor(0X99CCFF);
        addition.addActionListener(new ActionListener()
        { 
            public void actionPerformed(ActionEvent ae)
            {
                //
                String s =tf.getText();
                if( s!=null && s.length() > 0)
                {
                    try
                    {
                        // Store the time in the String k
                        String k = Refresh2();
                        // The record and the time stored in KK String
                        String kk =tf.getText()+"-"+k;
                        // Add an item (the kk String) to mylist List.
                        mylist.addItem(kk);
                        byte bytestream[] = kk.getBytes() ;
                        // Add a record to recordStore.
                        int i = recordStore.addRecord(bytestream, 0, bytestream.length);
                    }
                    catch(Exception ex) { }
                    // Inform the User that he added the a record.
                    Dialog validDialog = new Dialog(" ");
                    Style Dialogstyle = validDialog.getSelectedStyle() ;
                    validDialog.setScrollable(false);
                    validDialog.getDialogStyle().setBgColor(0x0066CC);
                    validDialog.setTimeout(1000); // set timeout milliseconds
                    TextArea textArea = new TextArea("...."); //pass the alert text here
                    textArea.setFocusable(false);
                    textArea.setText("A goal has been added"+"" );
                    validDialog.addComponent(textArea);
                    validDialog.show(0, 10, 10, 10, true);
                }
                // Information to user that he/she didn’t add a record
                else if((s==null || s.length()<= 0))
                {
                    Dialog validDialo = new Dialog(" ");
                    validDialo.setScrollable(false);
                    validDialo.getDialogStyle().setBgColor(0x0066CC);
                    validDialo.setTimeout(5000); // set timeout milliseconds
                    TextArea textArea = new TextArea("...."); //pass the alert text here
                    textArea.setFocusable(false);
                    textArea.setText("please enter scorer name or number");
                    validDialo.addComponent(textArea);
                    validDialo.show(50, 50, 50, 50, true);
                }
            }
        });
        /*Action here for displaying all records of recordStore RecordStore in a new form */
        All.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                try
                {
                    recordStore = RecordStore.openRecordStore("My Record Store", true);
                }
                catch(Exception ex) {} 
                try
                {
                    com.sun.lwuit.Label l = new com.sun.lwuit.Label(" Team Goals") ;
                    ff.addComponent(l);
                    // Store the records of recordStore in string array
                    String [] record= getRecordData();
                    int j1;
                    String valueToBeInserted2="";
                    int k=getRecordData().length;
                    for( j1=0;j1< getRecordData().length;j1++)
                    {
                        valueToBeInserted2=valueToBeInserted2 + " " + record[j1];
                        if(j1==getRecordData().length)
                        {
                            mylist.addItem(record[j1]);
                            int m = getRecordData().length;
                            // Counting the number of records
                            String goals =""+getRecordData().length;
                            /* I tried to use for…loop to count them by length of the recordStore and render it.
                               This list also should display the number of records on the form.
                               But it didn’t !!!
                            */
                            mylist.addItem(goals);
                        }
                    }
                    ff.addComponent(mylist);
                }
                catch(java.lang.IllegalArgumentException e)
                {
                }
                finally
                {
                    ff.show();
                }
            }
        }
        );
        g.show();
    }
    public void pauseApp()
    {
    }
    public void destroyApp(boolean unconditional) {
    }
}

Я написал этот код, но он дает NullPointerException at recordStore.enumerateRecords (null, null,true);

Поэтому я думаю, что проблема здесь.

пожалуйста помоги.

myButton.addActionListener( new ActionListener()
{
    public void actionPerformed(ActionEvet av)
    { 
        try
        {
            RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true); 
            int o =recordStore.getNumRecords () ; 
        } 
        catch(Exception e)
        { 
        } 
    } 
}); 

3 ответа

Решение

Вот решение моей проблемы, я делаю цикл для получения числа

элементы массива.

счетчик должен быть длиной массива

    count.addActionListener( new ActionListener()
    {
    public void actionPerformed(ActionEvent av)
   {

            try
           {

          recordStore = RecordStore.openRecordStore("recordStore", true);

            }
            catch(Exception e)

            { }

            try
             {

        RecordEnumeration enumeration = recordStore.enumerateRecords (null,  null,true);

               }
             catch(Exception e)
             {

             }
            String record[] = getRecordData();
            int j;


             j =   record.length-1;

                Dialog validDialog = new Dialog(" ");
                Style Dialogstyle = validDialog.getSelectedStyle() ;
                validDialog.setScrollable(false);
                validDialog.getDialogStyle().setBgColor(0x0066CC);
                validDialog.setTimeout(1000); // set timeout milliseconds
                TextArea textArea = new TextArea("....");  
                textArea.setFocusable(false);
                textArea.setText("Number Counted"+j );
                validDialog.addComponent(textArea);
                validDialog.show(0, 10, 10, 10, true);

                   }});

Вы можете использовать длину массива или установить RecordListener в своем хранилище записей и увеличить счетчик при добавлении записи в хранилище записей.

Что вам нужно, это enumeration.numRecords(); я считаю, что recordStore.getNumRecords() также должен работать, так как это то, что вы используете для заполнения массива, вы можете даже использовать длину самого массива. Все эти опции находятся в коде, было бы лучше изучить немного больше, а также проверить документацию для решения тривиальных проблем.

Другие вопросы по тегам