Pages

Tuesday 10 May 2011

ZIP Extractor code for j2me

//ZipME Package

ZipME Package Dowload Link
import net.sf.zipme.ZipInputStream;
import net.sf.zipme.ZipEntry;
public void zip(String filePath, int BUFFER) {
        this.url=filePath;
        javax.microedition.io.Connection c = null;
        FileConnection con = null;
        //Create RAR  Directory
        try {
            String URL = "file:///root1/";
            String rootDir = "file:///root1/RAR/Sample.txt";
            //  String  rootDir = "file:///e:/Other/rar/epub.txt";
            System.out.println("Create directory:Entry" + URL);
            String name = "RAR";
            URL.endsWith("/");
            alwaysURL = "";
            con = (FileConnection) javax.microedition.io.Connector.open(URL + name);
            con1 = (FileConnection) javax.microedition.io.Connector.open(rootDir);
            if (!(con.exists() && con.isDirectory())) {
                con.mkdir();
                System.out.println("Create Directory");
                rootDir = con.getName();
                // Try to create the directory, warn if it fails
                System.out.println("Creating Directory: " + rootDir);
            } else {
                System.out.println("Always Available");
            }
            if (!(con1.exists() && con1.isDirectory())) {
                con1.create();
             }
            root = URL + rootDir;
        } catch (Exception e) {
        }
        //Rar or Zip File  Extraction
        try {
            InputStream is = readRarFile(url);
            ZipInputStream zis = new ZipInputStream(is);
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                int i = (int) ze.getSize();
                b = new byte[i];
                //Zip File Readinn Process
                writeFile(zis, ze.getName(), b, root);
                zis.closeEntry();
            }
            zis.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
    }
//Fetch Zip File
    public InputStream readRarFile(String url) {
        javax.microedition.io.Connection c = null;
        java.io.InputStream is = null;
        try {
            c = javax.microedition.io.Connector.open(url, javax.microedition.io.Connector.READ);
            javax.microedition.io.file.FileConnection fc = (javax.microedition.io.file.FileConnection) c;
            is = fc.openInputStream();
         } catch (Exception e) {
            System.out.println("Error in reding the File");
       }
        return is;
    }
    //Load  Zip or Rar File after Extraction
    public boolean writeFile(ZipInputStream zis, String path, byte[] b, String URL2) {
        try {
            System.out.println(" new Directory" + URL2);
            System.out.println("filename:" + path);
            javax.microedition.io.Connection c = null;
            String url = URL2 + path;
            System.out.println("url:" + url);
            try {
                System.out.println("Enter the writing process");
                conn = (FileConnection) javax.microedition.io.Connector.open(url);
                // Write the File
                if (url.startsWith("/")) {
                    if (!warnedMkDir) {
                        System.out.println("Ignoring absolute paths");
                    }
                    warnedMkDir = true;
                    url = url.substring(1);
                }
                // if a directory, just return. We mkdir for every file,
                // since some widely-used Zip creators don't put out
                // any directory entries, or put them in the wrong place.
                if (url.endsWith("/")) {
                    return false;
                }
                // Else must be a file; open the file for output
                // Get the directory part.
                int ix = url.lastIndexOf('/');
                if (ix > 0) {
                    dirName = url.substring(0, ix);
                    //    if (!dirsMade.contains(dirName))
                    if (dirsMade != dirName) {
                        conn1 = (FileConnection) javax.microedition.io.Connector.open(dirName);
                       // If it already exists as a dir, don't do anything
                        if (!(conn1.exists() && conn1.isDirectory())) {
                            conn1.mkdir();
                            createFiles(zis);
                            // Try to create the directory, warn if it fails
                            System.out.println("Create Directory: " + dirName);
                            if (!(conn1.isDirectory())) {
                                System.err.println("Warning: unable to mkdir " + dirName);
                            }
                            dirsMade.equals(dirName);
                        }
                    }
               }
                createFiles(zis);
            } catch (IOException e) {
                // error
            } catch (SecurityException e) {
                // no permission to create/write
            }
            conn.close();
            return true;
        } catch (Exception e) {
            str = str + e.toString();
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                //  if (conn!= null)
                // conn.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
   private void createFiles(ZipInputStream zis) throws IOException {
        if (!conn.exists() && !conn.isDirectory()) {
            conn.create();
        } else {
            conn.truncate(0);
        }
        os = conn.openOutputStream();
        //Write Files
        int count;
        while ((count = zis.read(b, 0, b.length)) != -1) {
            os.write(b, 0, count);
        }
        os.flush();
    }

J2me run an android using Netbeans IDE



If you want  J2ME code was run an android  just follow the steps

Step 1:
First Create Android Application (  Netbeans Configure with Android  )

Step 2:


    <?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="org.me.list">
    <application>
         <activity android:name=".SearchListActivity" android:label="SearchListActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>


 
To be able to use the vibrator you have to add the following tag to your
            AndroidManifest.xml file:
            <uses-permission android:name="android.permission.VIBRATE" />

            In some special cases, you may want to bypass restarting of your activity
            based on one or more types of configuration changes. This is done with
             the android:configChanges attribute in its manifest. For any types of
               configuration changes you say that you handle there, you will receive a
               call to your current activity's onConfigurationChanged(Configuration)
              method instead of being restarted. If a configuration change involves any
              that you do not handle, however, the activity will still be restarted and
               onConfigurationChanged(Configuration) will not be called."          
               interesting info on 'sensor' orientation detection (or the lack of ..)
             http://androidguys.com/?p=2914
              
              I strongly suggest using the following attribute within the <activity/> tag in the
              AndroidManifext.xml file:
             
              android:configChanges="keyboardHidden|orientation"
                // http://android-developers.blogspot.com/2009/04/updating-applications-for-on-screen.html
     The virtual keyboard behavior can be configured from the AndroidManifest.xml file.  For example:
     <activity name="myactivity"
        android:windowSoftInputMode="adjustResize">
        ...
    </activity>
    This will shrink the LWUIT form once the keyboard appears.  By default the keyboard will be shown on top
    it seems.

<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  android:versionCode="1"
          android:versionName="1.0.0"
               package="org.me.list">
    <application>
        <activity android:name=".SearchListActivity " android:screenOrientation="sensor" android:configChanges="keyboardHidden|orientation" android:windowSoftInputMode="stateVisible|adjustResize"  android:label="SearchListActivity ">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
                <uses-permission android:name="android.permission.VIBRATE" />

            </intent-filter>
        </activity>
    </application>
</manifest>

Step 3:
Create Assets( we wanted to add some resources in the assets directory for use an Android Application if you not create assets raise File not found exception)
  1. Create a directory called ‘assets’ at your project root (same dir that AndroidManifest.xml lives)
  2. In /nbproject/project.properties, change
assets.dir=
to
 assets.dir=assets
assets.available=true
asset.dir=assets
  1. In /nbproject/build-impl.xml, there is line in the “if=assets.available” target that reads
4.      <arg value="${asset.dir}"/>
that needs to be changed to
<arg value="${assets.dir}"/>
That’s it – you should be all set and “file:///android_asset/” should be accessible to your application and contain the contents of your project’s assets directory.

Step 4:
1.Download Code from  following Link4Source copy  that files and load to the Src directory
2.Find Src\org\meteoroid\test\ and load ur J2ME MIDlet File and supported Files
Chage ActivityName,Package name in AndroidManifest.xml
3.Set MIDlet File location on assets\META-INF\MANIFEST-MF change
MIDlet-1: MIDlet_Title,/icon.png,org.App.test.MainMidlet
MIDlet-2: Canvas,/icon.png,org.App.test.TestMIDlet2
.
.
.
4.Load image,Txt,and other resources to load in Assets
Step 5:
Build Android Appliaction,then Run the Appliaction

Blackberry with Lwuit using Netbeans IDE

Step 1:
Fetch the LWUIT sources from SVN and create the BlackBerryPort project.
Or Download Link Project
Step 2: Blackberrry Port Project creation:
RIM port needs to replace some classes from LWUIT for Blackberry device supporting. 1. Remove: com.sun.lwuit.animations.Transition3D.java file from the LWUIT MIDP source code and clean & build. This is important, because, Blackberry doesn't support M3G classes. Clean & Build the BlackberryPort (BlackberryPort is within the LWUIT source code, both LWUIT andBlackberryPort are netbeans projects).
Step 3:
If not interested to create blackberry port and edit lwuit source Project please follow the step to create Blackberry with Lwuit project,some changes we need, but correctly follow steps
1.Create J2ME Application project
2. Insert the below code in \build.xml
 <target name="create-cod" if="blackberry.trigger">
        <exec dir="${dist.dir}" executable="java" failonerror="true">
            <arg value="-cp"/>
            <arg value="${platform.home}/bin/rapc.jar"/>
            <arg value="net.rim.tools.compiler.Compiler"/>
            <arg value="import=${platform.bootclasspath}"/>
            <arg value="codename=${name}"/>
            <arg value="-cldc"/>
            <arg value="jad=${basedir}/${dist.dir}/${dist.jad}"/>
            <arg value="${basedir}/${dist.dir}/${dist.jar}"/>
        </exec>
        <property file="${dist.dir}/${dist.jad}"/>
        <echo file="${basedir}/${dist.dir}/${name}.alx">
&lt;loader version="1.0"&gt;
    &lt;application id="${name}"&gt;
        &lt;name&gt;
            ${MIDlet-Name}
        &lt;/name&gt;
        &lt;description&gt;
            ${MIDlet-Description}
        &lt;/description&gt;
        &lt;version&gt;
            ${MIDlet-Version}
        &lt;/version&gt;
        &lt;vendor&gt;
            ${MIDlet-Vendor}
        &lt;/vendor&gt;
        &lt;copyright&gt;
            ${MIDlet-Copyright}
        &lt;/copyright&gt;
        &lt;fileset Java="1.0"&gt;
            &lt;directory/&gt;
            &lt;files&gt;${name}.cod&lt;/files&gt;
        &lt;/fileset&gt;
    &lt;/application&gt;
&lt;/loader&gt;
        </echo>
    </target>
    <target name="install-on-nokia-device" depends="init">
        <!-- If you are using a different directory for the Nokia PC suite just update the DIR -->
        <echo>Installing ${basedir}\dist\${config.active}\${name}</echo>
        <exec dir="${dist.dir}" executable="c:\Program Files (x86)\Nokia\Nokia PC Suite 7\ApplicationInstaller.exe"
            failonerror="true">
            <arg value="${basedir}\dist\${config.active}\${name}.jar"/>
        </exec>
    </target>
    <target name="install-on-rim-device" if="blackberry.trigger" depends="init">
        <!-- Uncomment and replace ??? with your password to sign the app  before deployment to device -->
        <!-- exec dir="${dist.dir}" executable="java" failonerror="true">
            <arg value="-jar"/>
            <arg value="${platform.home}/bin/SignatureTool.jar"/>
            <arg value="-a"/>
            <arg value="-p"/>
            <arg value="???"/>
            <arg value="-c"/>
            <arg value="-r"/>
            <arg value="."/>
        </exec -->
        <exec dir="${dist.dir}" executable="${platform.home}/bin/JavaLoader.exe" failonerror="true">
            <arg value="-u"/>
            <arg value="load"/>
            <arg value="${basedir}\dist\${config.active}\${name}.cod"/>
        </exec>
    </target>
3: In /nbproject/project.properties, change
all.configurations=\
Before:
to
all.configurations=\ ,BlackBerry,BlackBerryTouch
After :
4: In/nbproject/project.properties, insert bellow code
Before Code:
configs.BlackBerry.abilities=MMAPI=1.1,SATSAJCRMI=1.0,SATSACRYPTO=1.0,JSR82=1.1,JSR226=1.0,MIDP=2.1,JSR229=1.1.0,RIM=,SATSAAPDU=1.0,CLDC=1.1,JSR177=1.0,JSR179=1.0.1,J2MEWS=1.0,WMA=2.0,JSR172=1.0,ColorScreen,OBEX=1.0,JSR238=1.0,JSR239=1.0,JSR211=1.0,JSR234=1.0,ScreenWidth=240,JSR75=1.0,SATSAPKI=1.0,JSR184=1.1,ScreenHeight=320,ScreenColorDepth=8,JSR180=1.0.1,J2MEXMLRPC=1.0
configs.BlackBerry.extra.classpath=${file.reference.NokiaIAP_API.jar}
configs.BlackBerry.javac.source=1.3
configs.BlackBerry.javac.target=1.3
configs.BlackBerry.libs.classpath=${file.reference.BlackberryPort.jar}
configs.BlackBerry.obfuscation.custom=
configs.BlackBerry.obfuscation.level=0
configs.BlackBerry.platform.active=BlackBerry_JDE_4_6_0
configs.BlackBerry.platform.active.description=BlackBerry JDE 4.6.0
configs.BlackBerry.platform.apis=JSR75-1.0
configs.BlackBerry.platform.bootclasspath=${platform.home}/lib/net_rim_api.jar
configs.BlackBerry.platform.configuration=CLDC-1.1
configs.BlackBerry.platform.device=9000
configs.BlackBerry.platform.fat.jar=true
configs.BlackBerry.platform.profile=MIDP-2.0
configs.BlackBerry.platform.trigger=CLDC
configs.BlackBerry.platform.type=CUSTOM
configs.BlackBerry.sign.alias=minimal
configs.BlackBerry.sign.enabled=false
configs.BlackBerry.sign.keystore=${file.reference.builtin.ks}
configs.BlackBerryTouch.abilities=MMAPI=1.1,SATSAJCRMI=1.0,SATSACRYPTO=1.0,JSR82=1.1,JSR226=1.0,MIDP=2.1,JSR229=1.1.0,RIM=,SATSAAPDU=1.0,CLDC=1.1,JSR177=1.0,JSR179=1.0.1,J2MEWS=1.0,WMA=2.0,JSR172=1.0,ColorScreen,OBEX=1.0,JSR238=1.0,JSR239=1.0,JSR211=1.0,JSR234=1.0,ScreenWidth=240,JSR75=1.0,SATSAPKI=1.0,JSR184=1.1,ScreenHeight=320,ScreenColorDepth=8,JSR180=1.0.1,J2MEXMLRPC=1.0
configs.BlackBerryTouch.extra.classpath=${file.reference.NokiaIAP_API.jar}
configs.BlackBerryTouch.javac.source=1.3
configs.BlackBerryTouch.javac.target=1.3
configs.BlackBerryTouch.libs.classpath=${file.reference.BlackberryPort_Touch.jar};${file.reference.LWUIT.jar};${file.reference.LWUIT4IO.jar};${file.reference.NokiaIAP_API.jar}
configs.BlackBerryTouch.platform.active=BlackBerry_JDE_4_7_0
configs.BlackBerryTouch.platform.active.description=BlackBerry JDE 4.7.0
configs.BlackBerryTouch.platform.apis=JSR179-1.0
configs.BlackBerryTouch.platform.bootclasspath=${platform.home}/lib/net_rim_api.jar
configs.BlackBerryTouch.platform.configuration=CLDC-1.1
configs.BlackBerryTouch.platform.device=9500
configs.BlackBerryTouch.platform.fat.jar=true
configs.BlackBerryTouch.platform.profile=MIDP-2.0
configs.BlackBerryTouch.platform.trigger=CLDC
configs.BlackBerryTouch.platform.type=CUSTOM
configs.BlackBerryTouch.sign.alias=untrusted
configs.BlackBerryTouch.sign.enabled=true
configs.BlackBerryTouch.sign.keystore=${file.reference.builtin.ks}
5: keystore Process In/nbproject/project.properties, findfile.reference.builtin.ks while not in a code insert below code
file.reference.builtin.ks=${netbeans.user}/config/j2me/builtin.ks
6: In/nbproject/project.properties, change
sign.keystore=
to
sign.keystore=${file.reference.builtin.ks}
After Code:
7.Then we right click the projectèResolve Solve Reference Problem
We need add Blackberry and LWUIT supported Jars below in link:
Step 3:
MainMIDlet.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
/**
* @author Administrator
*/
public class MainMIDlet extends
//#ifdef RIM
net.rim.device.api.ui.UiApplication
//#else
//#javax.microedition.midlet.MIDlet
//#endif
{
public Resources res;
//#ifndef RIM
//#
//#endif
//#ifdef RIM
public static void main(String[] argv)
{
System.out.println("starting app...");
new MainMIDlet().startApp();
}
public void notifyDestroyed() {
System.exit(0);
}
public void platformRequest(String s) {
net.rim.blackberry.api.browser.Browser.getDefaultSession().displayPage(s);
}
//#endif
public void startApp() {
Display.init(this);
try {
res = com.sun.lwuit.util.Resources.open("/blue.res");
} catch (IOException ex) {
}
com.sun.lwuit.plaf.UIManager.getInstance().setThemeProps(res.getTheme(res.getThemeResourceNames()[0]));
Form f = new Form();
f.setTitle("Blackberry with LWUIT");
f.setLayout(new BorderLayout());
f.addComponent("Center",
new Label("Finally we got it"));
f.addCommand(new Command("Exit") {
public void actionPerformed(ActionEvent ae) {
notifyDestroyed();
}
});
f.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public static Resources getResource(String name) throws IOException {
return Resources.open("/" + name + ".res");
}
}
Sample BlackApp Project
Note:
While we can’t build Blackberry project or Simulator Problem Please install the Blackberry Ant Tools
Download BB AnT Tools, make sure you are using Ant 1.7 or higher.
This will provide support for tasks like:

  • rapc

  • sigtool

  • alx

  • jadtool
5.Unzip and copy the file "bb-ant-tools.jar" to the ${Netbeans-home}/java/ant/lib directory.
References
Try it...
To know more about the ANT build files, review the references.