dbmidlet.java

来自「J2ME MIDP_Example_Applications」· Java 代码 · 共 236 行

JAVA
236
字号
// Copyright 2003 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.
package example.midlet;

import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import example.mesql.*;

public class DBMIDlet
   extends MIDlet implements DBListener
{
  private final Image logo;
  private final DBScreen displayable;
  private final ActivityIndicator activityIndicator;
  private final example.mesql.Connection c;
  private final Vector records = new Vector();
  private int current = -1;

  public DBMIDlet()
  {
    // initialize final variables
    logo = makeImage("/logo.png");
    ErrorScreen.init(logo, Display.getDisplay(this));
    displayable = new DBScreen(this);
    activityIndicator = new ActivityIndicator(this);
    // creates the DB connection and set the listener
    c = new example.mesql.Connection(Display.getDisplay(this),
                                     getAppProperty("Proxy-URL"));
    c.setListener(this);
  }

  public void pauseApp()
  {
  }

  public void startApp()
  {
    Displayable current = Display.getDisplay(this)
      .getCurrent();
    if (current == null)
    {
      // the first time we are called display a splash screen
      String text = getAppProperty("MIDlet-Name") + "\n" +
                                   getAppProperty("MIDlet-Vendor");
      Alert splashScreen = new Alert(null,
                                     text,
                                     logo,
                                     AlertType.INFO);
      splashScreen.setTimeout(3000);
      Display.getDisplay(this).setCurrent(displayable);
    }
    else
    {
      Display.getDisplay(this).setCurrent(current);
    }
  }

  // loads a given image by name
  static Image makeImage(String filename)
  {
    Image image = null;
    try
    {
      image = Image.createImage(filename);
    }
    catch (Exception e)
    {
      // use a null image instead
    }
    return image;
  }

  public void destroyApp(boolean unconditional)
  {
    c.destroy();
  }

  // move to the next record
  void goNextRecord()
  {
    if (records.size() > 0 &&
      current < records.size() - 1)
    {
      displayable.setCurrent((UserRecord) records.elementAt(++current),
                             current,
                             records.size());
    }
  }

  // move to the previous record
  void goPreviousRecord()
  {
    if (records.size() > 0 && current > 0)
    {
      displayable.setCurrent((UserRecord) records.elementAt(--current),
                             current,
                             records.size());
    }
  }

  // conects to the database and select 10 rows from
  // the tabler user
  void readRecords()
  {
    activityIndicator.startProgressMeter();
    Display.getDisplay(this).setCurrent(activityIndicator);
    records.removeAllElements();
    String query = "select * from user";
    Statement s = c.createStatement();
    s.setMaxRows(10);
    s.executeQuery(query);
  }

  // inserts a new record using a PreparedStatement
  void insertNewRecord(UserRecord record)
  {
    int result = 0;
    activityIndicator.startProgressMeter();
    Display.getDisplay(this).setCurrent(activityIndicator);
    String query = "insert into user values(?, ?, ?, ?, ?)";
    PreparedStatement s = c.prepareStatement(query);
    s.setString(1, record.getFamilyName());
    s.setString(2, record.getFirstName());
    s.setString(3, record.getPhoneNumber());
    s.setString(4, record.getEMail());
    s.setInt(5, record.getAge());
    s.executeUpdate();
    records.insertElementAt(record, 0);
  }

  // deletes the current recoird
  void deleteCurrentRecord()
  {
    if (records.size() > 0) {
      int result = 0;
      activityIndicator.startProgressMeter();
      UserRecord record = (UserRecord) records.elementAt(current);
      Display.getDisplay(this).setCurrent(activityIndicator);

      // let's assume phone number is the key in the table
      String query = "delete from user where phonenumber = ?";
      PreparedStatement s = c.prepareStatement(query);
      s.setString(1, record.getPhoneNumber());
      s.executeUpdate();
    }
  }


  public void receiveQueryResponse(ResultSet rs)
  {
    try
    {
      records.removeAllElements();
      while (rs.next())
      {
        String familyName = rs.getString(1);
        String firstName = rs.getString(2);
        String phoneNumber = rs.getString(3);
        String eMail = rs.getString(4);
        int age = rs.getInt(5);
        UserRecord record = new UserRecord(familyName,
                                           firstName,
                                           phoneNumber,
                                           eMail,
                                           age);
        records.addElement(record);
      }
    }
    catch (SQLException e)
    {
      ErrorScreen.showError(e.getMessage(), displayable);
    }
    if (records.size() > 0)
    {
      current = 0;
      displayable.setCurrent((UserRecord) records.elementAt(0),
                             current,
                             records.size());
    }
    else
    {
      // if there are now records, clean the screen
      displayable.cleanForm();
    }
    activityIndicator.stopProgressMeter();
    Display.getDisplay(this).setCurrent(displayable);
  }

  // displays error message
  public void receiveSQLException(SQLException exception)
  {
    activityIndicator.stopProgressMeter();
    ErrorScreen.showError(exception.getMessage(), displayable);
  }

  // in case of update we reload the content
  public void receiveUpdateResponse(int count, int type)
  {
    // reload the contents of the set
    readRecords();
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?