Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2007

Tip: Looking for answers? Try searching our database.

J2ME: read and show CSV-files

Thread view: 
Tobias Wendorff - 20 May 2007 23:31 GMT
Hi there,

I'm into JAVA programming for some days only, but I've read
many tutorials and documents. It's very great, but my cell-phone
(it's a Siemens S65) can't view all the multi-media things :-(

I would like to read the content of a CSV-file and print it out
on the screen. I don't care, it's embedded in the midlet or
on the mobile itself. I know how to handle this :-)

The CSV looks like this:
surname;firstname;street
Doe;John;nobody knows

I would like to see this on the mobile:
Firstname: John
Surname: Doe
Street: nobody knows

Does anybody have an example for this? I don't want a finished
code - but of course, I wouldn't say no :-)

Best regards,
Tobias
Jeff Higgins - 21 May 2007 01:49 GMT
> Hi there,
>
[quoted text clipped - 20 lines]
> Best regards,
> Tobias

Commented stuff I'm not real sure about.

//Connection c =Connector.open(file://records.dat);
//DataInputStream dis = new DataInputStream(c.openInputStream());
//String data = dis.readUTF();

String[] records = data.split("\n");
String[] fields = new String[3];
for(int i=0;i<records.length;i++)
{
 fields = records[i].split(";");
}

//Form.append("Firstname: " + fields[1]);
//Form.append("Surname: " + fields[0]);
//Form.append("Street: " + fields[2]);
Jeff Higgins - 21 May 2007 16:18 GMT
>> Hi there,
>>
[quoted text clipped - 37 lines]
> //Form.append("Surname: " + fields[0]);
> //Form.append("Street: " + fields[2]);

Oops! no String.split method!

import java.util.Vector;

public class testString
{
 public static void main(String[] args)
 {
   String data =
     "Doe;John;Bywater Road" +
     "\n" +
     "Atkins;Rae Dawn;Tinpan Alley" +
     "\n" +
     "Phillips;Michelle;Bright Boulevard";

   String[] records = split(data, "\n");

   for(int ri = 0; ri < records.length; ri++)
   {
     String[] fields = split(records[ri], ";");
     System.out.println("Firstname: " + fields[1]);
     System.out.println("Surname: " + fields[0]);
     System.out.println("Street: " + fields[2] + "\n");
   }
 }

 // Split method from Substance
 //
<http://forum.java.sun.com/thread.jspa?threadID=646861&messageID=3809007>

 static private String[] split(String original, String separator)
 {
   Vector nodes = new Vector();
   int index = original.indexOf(separator);
   while(index>=0)
   {
     nodes.addElement( original.substring(0, index) );
     original = original.substring(index+separator.length());
     index = original.indexOf(separator);
   }
   nodes.addElement( original );
   String[] result = new String[ nodes.size() ];
   if( nodes.size()>0 )
   {
     for(int loop=0; loop<nodes.size(); loop++)
       result[loop] = (String)nodes.elementAt(loop);
   }
   return result;
 }
}
Jeff Higgins - 21 May 2007 20:16 GMT
Another split method - no Vector

public class testString
{
 public static void main(String[] args)
 {
   String data =
     "Doe;John;Bywater Road" +
     "\n" +
     "Atkins;Rae Dawn;Tinpan Alley" +
     "\n" +
     "Phillips;Michelle;Bright Boulevard";

   String[] records = split2(data, "\n");

   for(int ri = 0; ri < records.length; ri++)
   {
     String[] fields = split2(records[ri], ";");
     System.out.println("Firstname: " + fields[1]);
     System.out.println("Surname: " + fields[0]);
     System.out.println("Street: " + fields[2] + "\n");
   }
 }

 // Split method from Jorma Ikonen
 //
<http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=41&t=001519>

 static String[] split(String splitStr, String delimiter){

   /** Note, delimiter can't be regex-type of argument as
   * in orginal J2SE implementation!!!*/
   int dLen = delimiter.length();
   int p1 = 0;
   int cnt = 0;

   if (splitStr.length() == 0){
   String[] excepStr = new String[1];
   excepStr[0] = "";
   return excepStr;
   }

   if (dLen == 0){
   String[] excepStr = new String[splitStr.length()+1];
   excepStr[0] = "";
   for (int i = 0; i<excepStr.length-1; i++){
   excepStr[i+1] = String.valueOf(splitStr.charAt(i));
   }
   return excepStr;
   }

   p1 = splitStr.indexOf(delimiter, p1);
   while (p1 != -1){
   cnt++;
   p1 = p1 + dLen;
   p1 = splitStr.indexOf(delimiter, p1);
   }

   String[] tmp = new String[cnt + 1];
   p1 = 0;
   int p2 = 0;
   for (int i = 0; i<tmp.length; i++){
   p2 = splitStr.indexOf(delimiter, p2);
   if (p2 == -1){
   tmp[i] = splitStr.substring(p1);
   }else{
   tmp[i] = splitStr.substring(p1, p2);
   }
   p1 = p2 + dLen;
   p2 = p2 + dLen;
   }
   cnt = 0;

   for (int i = tmp.length-1; i>-1; i--){
   if(tmp[i].length() > 0){
   break;
   } else{
   cnt++;
   }
   }
   String[] result = new String[tmp.length-cnt];
   for (int i = 0; i<result.length; i++){
   result[i] = tmp[i];
   }
   return result;

   }
}
Tobias Wendorff - 23 May 2007 18:49 GMT
Hi Jeff,

I'm getting this in J2ME:

java.lang.InstantiationException: Class not a MIDlet
at com.sun.midp.midlet.MIDletState.createMIDlet(+66)
at com.sun.midp.midlet.Selector.run(+22)

How can I fix it?

Best,
Tobias
Jeff Higgins - 23 May 2007 21:58 GMT
> Hi Jeff,
>
[quoted text clipped - 8 lines]
> Best,
> Tobias

Hi Tobias,
 First let me thank you for providing me the
impetus for looking at J2ME, your OP was the
first that I've examined it - having fun!

I don't know - have you extended the MIDlet class?

Here's what I have so far - please don't use this
as a good example.

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class ReadDisplayFile extends MIDlet
 implements CommandListener, ItemCommandListener{
 private Form mMainForm;
 private Command cmNext =
   new Command("Next", Command.SCREEN, 1);
 private Command cmExit =
   new Command("Exit", Command.EXIT, 1);
 private Command cmDial =
   new Command("Dial", Command.ITEM, 1);
 private StringItem siFirstname =
   new StringItem(null,null);
 private StringItem siSurname =
   new StringItem(null,null);
 private StringItem siStreet =
   new StringItem(null,null);
 private StringItem siPhone =
   new StringItem(null,null);
 private int nextRecord = 0;
 private int recordCount = 0;
 private String[][] records;

 public ReadDisplayFile() {
   records = splitFile();
   mMainForm = new Form("Phonebook");
   siFirstname.setText("Firstname: " +
       records[nextRecord][1] + "\n");
   siSurname.setText("Surname: " +
       records[nextRecord][0] + "\n");
   siStreet.setText("Street: " +
       records[nextRecord][2] + "\n");
   siPhone.setText("Phone: " +
       records[nextRecord][3] + "\n");
   siPhone.addCommand(cmDial);
   siPhone.setItemCommandListener(this);

   nextRecord++;

   mMainForm.append(siFirstname);
   mMainForm.append(siSurname);
   mMainForm.append(siStreet);
   mMainForm.append(siPhone);

   mMainForm.addCommand(cmNext);
   mMainForm.addCommand(cmExit);
   mMainForm.setCommandListener(this);
 }

 protected void destroyApp(boolean arg0)
   throws MIDletStateChangeException {}

 protected void pauseApp() {}

 protected void startApp()
   throws MIDletStateChangeException {
   Display.getDisplay(this).setCurrent(mMainForm);
 }

 public void commandAction(Command c, Displayable arg1)
 {
   if (c == cmNext)
   {
     if(nextRecord <= recordCount)
     {
       siFirstname.setText("Firstname: " +
           records[nextRecord][1] + "\n");
       siSurname.setText("Surname: " +
           records[nextRecord][0] + "\n");
       siStreet.setText("Street: " +
           records[nextRecord][2] + "\n");
       siPhone.setText("Phone: " +
           records[nextRecord][3] + "\n");
       nextRecord++;
     }
     else
     {
       nextRecord = 0;
       siFirstname.setText("Firstname: " +
           records[nextRecord][1] + "\n");
       siSurname.setText("Surname: " +
           records[nextRecord][0] + "\n");
       siStreet.setText("Street: " +
           records[nextRecord][2] + "\n");
       siPhone.setText("Phone: " +
           records[nextRecord][3] + "\n");
       nextRecord++;
     }
   }
   else if (c == cmExit)
   {
     notifyDestroyed();
   }
 }

 private String[][] splitFile()
 {
   InputStream is =
     getClass().getResourceAsStream("records.txt");
   try
   {
     StringBuffer sb = new StringBuffer();
     int chr = 0;
     while ((chr = is.read()) != -1)
     {
       sb.append((char) chr);
     }
     is.close();
     String[] data = split(sb.toString(),"\r\n");
     String[][] records = new String[data.length][4];
     for(int recordIndex = 0;
       recordIndex < data.length;
       recordIndex++)
     {
       for(int fieldIndex = 0;
         fieldIndex < 4;
         fieldIndex++)
       {
         records[recordIndex] = split(data[recordIndex],";");
       }
       recordCount = recordIndex;
     }
     return records;
   }
   catch (IOException e)
   {
     System.err.print(e.toString());
   }
   return null;
 }

 static private String[] split(String original, String separator)
 {
   Vector nodes = new Vector();
   int index = original.indexOf(separator);
   while(index>=0)
   {
     nodes.addElement( original.substring(0, index) );
     original = original.substring(index+separator.length());
     index = original.indexOf(separator);
   }
   nodes.addElement( original );
   String[] result = new String[ nodes.size() ];
   if( nodes.size()>0 )
   {
     for(int loop=0; loop<nodes.size(); loop++)
       result[loop] = (String)nodes.elementAt(loop);
   }
   return result;
 }

 public void commandAction(Command c, Item arg1) {

   if(c == cmDial)
   {
     try {
       platformRequest("tel:<1-(555)555-5555>");
     } catch (ConnectionNotFoundException e) {
       e.printStackTrace();
     }
   }

 }
}
Jeff Higgins - 24 May 2007 01:30 GMT
> > Hi Jeff,
>
[quoted text clipped - 5 lines]
>
> > How can I fix it?

Another thing you can check is if you are throwing an exception from
your constructor - in my code I'm reading the CSV file in the
constructor
via splitFile() method. If I don't place the CSV file in the jar, or
If I
put it in the wrong place I get a similar exception.

sending this via Google Groups cause my news server is acting up.
Again. :-(

JH
Tobias Wendorff - 24 May 2007 21:03 GMT
Hi Jeff,

[code]

Thanks, it's working fine here!

This part:

InputStream is = getClass().getResourceAsStream("records.txt");

is reading "records.txt" from RES-directory or from the JAR
directly. How can I make it loading from the web or a directory?

Normally, this code should work (I'm using it in another app):

String file = "file:///root1/records.txt";
StreamConnection sc = (StreamConnection)Connector.open(file);
InputStream is = sc.openInputStream();

or

String file = "file:///root1/records.txt";
InputConnection sc = (InputConnection)Connector.open(url);
InputStream is = sc.openInputStream();

... but both don't work :-(

Best,
Tobias
Jeff Higgins - 24 May 2007 23:53 GMT
> Hi Jeff,
>
[quoted text clipped - 25 lines]
> Best,
> Tobias

I'm not sure. I haven't got that far yet. But maybe these
articles can be of some help.

<http://developers.sun.com/techtopics/mobility/midp/articles/network/>

<http://today.java.net/pub/a/today/2007/03/29/working-with-java-me-fileconnection
-on-physical-devices.html
>

<http://developers.sun.com/techtopics/mobility/midp/articles/midp2network/>


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.