Sunday, August 31, 2008

Considerations about Multibyte Charactersets

Lets see an example of MultiByte character set,
SQL> create table t_1 (col1 varchar2(1));
Table created.

SQL> create table t_2 (col1 varchar2(1 CHAR));
Table created.

SQL> insert into t_1 values ('é');
insert into t_1 values ('é')
*
ERROR at line 1:
ORA-12899: value too large for column "MY_UTF"."T_1"."COL1" (actual: 3,maximum: 1)

SQL> insert into t_2 values ('é');
1 row created.

The important thing is that, the character 'é' is not a single byte character. Thats why, it could be stored in a column that is with a fixed char length not a fixed byte length.

Check the Database Characterset

We can see the character set of a database by using the following SQL.
select parameter,value from nls_database_parameters where parameter like '%CHARACTERSET%';

Super Set List of Character Set

These Character Set combination are valid for the 'ALTER DATABSE CHARACTER SET xxxx ' command. A superset is a character set where every character in the subset character set is defined and is defined at the same code point.

If the change you want to do (change from -> characterset) is not listed here, then you need to use Export/Import.

8.1.6 Subset/Superset Pairs
===========================

A. Current Char set B. New Char set (Superset of A.)
------------------- --------------------------------
US7ASCII WE8DEC
US7ASCII US8PC437
US7ASCII WE8PC850
US7ASCII IN8ISCII
US7ASCII WE8PC858
US7ASCII WE8ISO8859P1
US7ASCII EE8ISO8859P2
US7ASCII SE8ISO8859P3
US7ASCII NEE8ISO8859P4
US7ASCII CL8ISO8859P5
US7ASCII AR8ISO8859P6
US7ASCII EL8ISO8859P7
US7ASCII IW8ISO8859P8
US7ASCII WE8ISO8859P9
US7ASCII NE8ISO8859P10
US7ASCII TH8TISASCII
US7ASCII BN8BSCII
US7ASCII VN8VN3
US7ASCII VN8MSWIN1258
US7ASCII WE8ISO8859P15
US7ASCII WE8NEXTSTEP
US7ASCII AR8ASMO708PLUS
US7ASCII EL8DEC
US7ASCII TR8DEC
US7ASCII LA8PASSPORT
US7ASCII BG8PC437S
US7ASCII EE8PC852
US7ASCII RU8PC866
US7ASCII RU8BESTA
US7ASCII IW8PC1507
US7ASCII RU8PC855
US7ASCII TR8PC857
US7ASCII CL8MACCYRILLICS
US7ASCII WE8PC860
US7ASCII IS8PC861
US7ASCII EE8MACCES
US7ASCII EE8MACCROATIANS
US7ASCII TR8MACTURKISHS
US7ASCII EL8MACGREEKS
US7ASCII IW8MACHEBREWS
US7ASCII EE8MSWIN1250
US7ASCII CL8MSWIN1251
US7ASCII ET8MSWIN923
US7ASCII BG8MSWIN
US7ASCII EL8MSWIN1253
US7ASCII IW8MSWIN1255
US7ASCII LT8MSWIN921
US7ASCII TR8MSWIN1254
US7ASCII WE8MSWIN1252
US7ASCII BLT8MSWIN1257
US7ASCII N8PC865
US7ASCII BLT8CP921
US7ASCII LV8PC1117
US7ASCII LV8PC8LR
US7ASCII LV8RST104090
US7ASCII CL8KOI8R
US7ASCII BLT8PC775
US7ASCII WE8DG
US7ASCII WE8NCR4970
US7ASCII WE8ROMAN8
US7ASCII WE8MACROMAN8S
US7ASCII TH8MACTHAIS
US7ASCII HU8CWI2
US7ASCII EL8PC437S
US7ASCII LT8PC772
US7ASCII LT8PC774
US7ASCII EL8PC869
US7ASCII EL8PC851
US7ASCII CDN8PC863
US7ASCII HU8ABMOD
US7ASCII AR8ASMO8X
US7ASCII AR8NAFITHA711T
US7ASCII AR8SAKHR707T
US7ASCII AR8MUSSAD768T
US7ASCII AR8ADOS710T
US7ASCII AR8ADOS720T
US7ASCII AR8APTEC715T
US7ASCII AR8NAFITHA721T
US7ASCII AR8HPARABIC8T
US7ASCII AR8NAFITHA711
US7ASCII AR8SAKHR707
US7ASCII AR8MUSSAD768
US7ASCII AR8ADOS710
US7ASCII AR8ADOS720
US7ASCII AR8APTEC715
US7ASCII AR8MSAWIN
US7ASCII AR8NAFITHA721
US7ASCII AR8SAKHR706
US7ASCII AR8ARABICMACS
US7ASCII LA8ISO6937
US7ASCII JA16VMS
US7ASCII JA16EUC
US7ASCII JA16SJIS
US7ASCII KO16KSC5601
US7ASCII KO16KSCCS
US7ASCII KO16MSWIN949
US7ASCII ZHS16CGB231280
US7ASCII ZHS16GBK
US7ASCII ZHT32EUC
US7ASCII ZHT32SOPS
US7ASCII ZHT16DBT
US7ASCII ZHT32TRIS
US7ASCII ZHT16BIG5
US7ASCII ZHT16CCDC
US7ASCII ZHT16MSWIN950
US7ASCII AL24UTFFSS
US7ASCII UTF8
US7ASCII JA16TSTSET2
US7ASCII JA16TSTSET



8.1.7 Additions
===============

US7ASCII ZHT16HKSCS
US7ASCII KO16TSTSET
WE8DEC TR8DEC
WE8DEC WE8NCR4970
WE8PC850 WE8PC858
D7DEC D7SIEMENS9780X
I7DEC I7SIEMENS9780X
WE8ISO8859P1 WE8MSWIN1252
AR8ISO8859P6 AR8ASMO708PLUS
AR8ISO8859P6 AR8ASMO8X
IW8EBCDIC424 IW8EBCDIC1086
IW8EBCDIC1086 IW8EBCDIC424
LV8PC8LR LV8RST104090
DK7SIEMENS9780X N7SIEMENS9780X
N7SIEMENS9780X DK7SIEMENS9780X
I7SIEMENS9780X I7DEC
D7SIEMENS9780X D7DEC
WE8NCR4970 WE8DEC
WE8NCR4970 TR8DEC
AR8SAKHR707T AR8SAKHR707
AR8MUSSAD768T AR8MUSSAD768
AR8ADOS720T AR8ADOS720
AR8NAFITHA711 AR8NAFITHA711T
AR8SAKHR707 AR8SAKHR707T
AR8MUSSAD768 AR8MUSSAD768T
AR8ADOS710 AR8ADOS710T
AR8ADOS720 AR8ADOS720T
AR8APTEC715 AR8APTEC715T
AR8NAFITHA721 AR8NAFITHA721T
AR8ARABICMAC AR8ARABICMACT
AR8ARABICMACT AR8ARABICMAC
KO16KSC5601 KO16MSWIN949
WE16DECTST2 WE16DECTST
WE16DECTST WE16DECTST2


9.0.1 Additions
===============

US7ASCII BLT8ISO8859P13
US7ASCII CEL8ISO8859P14
US7ASCII CL8ISOIR111
US7ASCII CL8KOI8U
US7ASCII AL32UTF8
BLT8CP921 BLT8ISO8859P13
US7ASCII AR8MSWIN1256
UTF8 AL32UTF8 (added in patchset 9.0.1.2)


Character Set Subset/Superset Pairs Obsolete from 9.0.1
=======================================================

US7ASCII AR8MSAWIN
AR8ARABICMAC AR8ARABICMACT


9.2.0 Additions
===============

US7ASCII JA16EUCTILDE
US7ASCII JA16SJISTILDE
US7ASCII ZHS32GB18030
US7ASCII ZHT32EUCTST
WE8ISO8859P9 TR8MSWIN1254
LT8MSWIN921 BLT8ISO8859P13
LT8MSWIN921 BLT8CP921
BLT8CP921 LT8MSWIN921
AR8ARABICMAC AR8ARABICMACT
ZHT32EUC ZHT32EUCTST
UTF8 AL32UTF8

Character Set Subset/Superset Pairs Obsolete from 9.2.0
=======================================================
LV8PC8LR                        LV8RST104090

Saturday, August 30, 2008

Convert all column from BYTE to CHARACTER

SET SERVEROUT ON
SPOOL CONV_B2C.SQL
BEGIN
EXECUTE IMMEDIATE 'PURGE RECYCLEBIN';
FOR X IN(SELECT table_name,column_name,data_length FROM COLS WHERE DATA_TYPE='VARCHAR2' AND CHAR_USED='B')
LOOP
DBMS_OUTPUT.PUT_LINE('ALTER TABLE '||X.TABLE_NAME||' MODIFY '||X.COLUMN_NAME||' VARCHAR2('||X.DATA_LENGTH||' CHAR);');
END LOOP;
END;
/
SPOOL OFF;


then run the script,
SQL>@CONV_B2C.SQL

Wednesday, August 27, 2008

Oracle Explain Plan with script

Create the plan table if it does not already exist
-- 9i or earlier
@?\rdbms\admin\utlxplan.sql
-- 10g or above
@?\rdbms\admin\catplan.sql

Explain Plan Syntax
set autotrace on
EXPLAIN PLAN
SELECT column_names FROM table;







Tuesday, August 19, 2008

Generating unique IDs with UUID

The identifiers generated by UUID are actually universally unique identifiers.

Example

import java.util.UUID;

public class GenerateUUID {
public static final void main(String... aArgs){
//generate random UUIDs
UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();
log("UUID One: " + idOne);
log("UUID Two: " + idTwo);
}
private static void log(Object aObject){
System.out.println( String.valueOf(aObject) );
}
}

Use System time to generate unique Number with JAVA

Since the granulaty of a PC can be as high as 55ms (down to 10ms), you can't use the System time to generate a unique ID because of the risk of getting duplicated IDs. This can be solved by using the following technique to make sure that the number returned is unique (in a single JVM).

public class UniqueID {
static long current= System.currentTimeMillis();
static public synchronized long get(){
return current++;
}
}

Saturday, August 16, 2008

Spring Framework Workflow

Have a look on the style of Spring Web Flow.
1. The Client requests for a Resource in the Web Application.
2. The Spring Front Controller, which is implemented as a Servlet, will intercept the Request and then will try to find out the appropriate Handler Mappings.
3. The Handle Mappings is used to map a request from the Client to its Controller object by browsing over the various Controllers defined in the Configuration file.
4. With the help of Handler Adapters, the Dispatcher Servlet will dispatch the Request to the Controller.
5. The Controller processes the Client Request and returns the Model and the View in the form of ModelAndView object back to the Front Controller.
6. The Front Controller then tries to resolve the actual View (which may be Jsp, Velocity or Free marker) by consulting the View Resolver object.
7. Then the selected View is rendered back to the Client.

Difference between words of Europe and America in form of past tense and past participle

There are lot of alternative forms of the past tense and past participle of the many verb. Learnt is more common in British English, and learned in American English. There are a number of verbs of this type (burn, dream, kneel, lean, leap, spell, spill, spoil etc.). They are all irregular verbs, and this is a part of their irregularity.

Wednesday, August 13, 2008

Size of the table including LOB segment

If you have a table having a column of LOB datatype, then we cant get the actual size of table from the following query.
SELECT SUM(BYTES)/1024/1024 FROM DBA_SEGMENTS
WHERE SEGMENT_NAME='OLD_DATA';

Because the lob are stored in different segments other than the table segment. so we can get the size from the following  query,

SELECT SUM(BYTES)/1024/1024 MB
FROM DBA_SEGMENTS
WHERE SEGMENT_NAME IN(
SELECT SEGMENT_NAME FROM DBA_LOBS DL
WHERE DL.TABLE_NAME='OLD_DATA'
AND DL.OWNER='PROD')
OR SEGMENT_NAME LIKE 'OLD_DATA' ;

Peer to Peer File Sharing in mobile [PeerBox]

PeerBox Mobile is a peer-to-peer file sharing service for your mobile phone. With PeerBox, you can share your videos and pictures with the world right from your mobile phone. You can also create your own picture profile, send messages to friends and watch their videos and pictures.

http://handheld.softpedia.com/get/Download-manager/PeerBox-Mobile-14398.shtml

Another one...[mbit.tv]
http://handheld.softpedia.com/get/Download-manager/mbit-tv-64225.shtml

Tips for IELTS Listening on True/False Question

For example:
Statement:There are six children in John’s family.
Tapescript: John’s got four kids, hasn’t he ?...Or is it five ?...no, no, I forgot Sara is the youngest yes, five and Sara.

So, if you answer the question too quickly, you will get the answer wrong. Also, you don’t hear the exact number ‘six’.The above example is of a question that is ‘True’. Look at the same question, but where the answer is ‘False’:

Statement:There are six children in John’s family.
Tapescript: John’s got six kids, hasn’t he?...Yes, six ?...no, no, I forgot – it’s Tony.
Who’s got six – John’s got three.

Here, you hear the same number as in the statement three times before you hear the correct one. So, again, answering too quickly will mean it is wrong. Have a look at these other ‘traps’ that you can get in True/False questions.

i) Changing the modifier only
Statement: All students have to register before 08 August.
Tapescript: Most students have to register before 08 August.
Answer: False

ii) Changing the answer twice.
Statement: Peter decides to go to the cinema.
Tapescript:
PETER: Let’s go to the cinema, there’s a new film on.
JANE: I’d like to go to the theatre instead to see the play.
PETER: OK, that’s fine, we’ll go to the theatre.
JANE: Great, thanks, oh no – maybe the cinema would be better.
PETER: OK – the cinema it is then
JANE: Are you sure?
PETER: Yes, sure. No, the theatre – definitely!

Answer: False

iii) Using words that mean the same (synonyms)

Statement:All students have to register before 08 August.
Tapescript: All students have to enroll before 08 August.
Answer: True

iv) Using opposites (antonyms)
Statement:Robert is very upset.
Tapescript: I’m worried about Robert, he isn’t happy at all these days.
Answer: True

v) Changing the wording
Statement: You have to pay on or before 08 August.
Tapescript: You can’t make payment after the 7th of August.
Answer: False

Tuesday, August 12, 2008

Find Invalid Objects in Oracle

Find Invalid Objects:
1.To Find the number of invalid objects :
select count(*) from dba_objects where status=’INVALID’;
select owner,object_type,count(*) from dba_objects where status='INVALID' group by owner,object_type;

2.To identify the object name and their types and owner:
select owner, object_name,object_type from dba_objects where status =’INVALID’;

Try Manual method of validation:
Alter procedure owner.procedure_name compile;
Alter function owner.function_name compile;
Alter view owner.view_name compile;
Alter package owner.package_name compile;
Alter package owner.package_name compile body;
Alter materialized view owner.Package_name Compile;

Find Dependencies & Debug error message:
If the error message is generic like ,table or view does not exist/nocolumns in table ,then to debug further we need to find all the objectson which the invalid object is dependent on.
We can get the information using the following query:
Select referenced_owner, referenced_name,referenced_type from
dba_dependencies where name=’Object_name’ and type =‘Object_type’ and owner =’owner_name’;
Check for the existence of the dependent objects and their status by querying dba_objects .

Understanding what you need to write about in IELTS

Task 2s are split into two parts…
1) The statement
and
2) The question
Together they make up the task.

Example:

Statement: 
More and more students are taking a year off after finishing school to travel or work before they go to university. However, some people don’t agree with this.
Question:

What are the advantages and disadvantages of this?


What you need to do is to read the statement carefully and underline what you think are the keywords. Keywords in task 2 statements are usually nouns, verbs, modifiers (eg: more / less/ a few / some) and negatives (e.g.: not / don’t).
Statement:   
More and more students are taking a year off after finishing school to travel or work before they go to university. However, some people don’t agree with this.
Question:

What are the advantages and disadvantages of this?

Tip: You should underline around 30% to 40% of the statement. It is very easy to underline about 80% at first because you’re not sure exactly what to do and all the words appear to be very important. Don’t worry too much if you’re underlining over 50% at first because as you practice further, the number of words you underline will decrease as you become more confident.

How to describe Pie Chart

i)Do I have to include all of the information in a pie chart?
No, you don't. Pie charts often have categories such as 'miscellaneous' and 'others'; you don't have to include these areas in your answers because it's not really clear what they refer to and they are normally included just to make up 100%.

ii) If there's only 1 pie chart?
It's probably best to look for 2 or 3 groups within the chart, for example: small / medium / large. Take a look at the chart below:

In this chart you can put BMW and Benz into the 'small' group, Toyota and Honda into the 'medium' group and Nissan and Mitsubishi into the 'large' group.

iii) If there are 2 pie charts?
If there are 2 charts that are related, then you should compare them. Look at the example below:

Here, you can compare between car makes that increased (BMW and Honda), the ones that decreased (Mitsubishi and Nissan) and those that remained stable (Benz and Toyota).

If you get 2 pie charts that are not related, deal with them separately in 2 paragraphs - don't try to compare or you could get into a mess.

Problems: Some people only repeat the percentage for each category and so don't show a variety of vocabulary.

You could write: "The great majority of sales were of Moschino bags at 82%, whereas Gucci sales accounted for only 18%."

You could write: "The majority of dishes sold were Kow Pad Moo at around one-third of all sales. Kow Pad Goong and Kow Pad Gai accounted for just over and just under one-quarter of sales respectively. Finally, only a few dishes of Kow Pad American were sold."

Useful language:
a few a small/large proportion of
a fair amount of
the (vast/great) majority of
one quarter
(around/about) one-third
(just under/over) a half three-quarters

Linking Words for essay writing

Tips:
*Don't over-use linking phrases. Use them sensibly where they are needed.
*Don't try to be clever by using more unusual words and phrases, you'll probably misuse them and get a lower score.
*Don't use the same phrases again and again. Don't try to learn long lists of phrases because you only need a few for your answer in the test. The examiner is looking for a variety of phrases, so just make sure you keep it simple and use a few common ones that are used with simple structures.

EXAMPLE:
Paragraph 1
There are many causes of air pollution. There is the use of private cars. This can cause many breathing problems because of fumes. Other forms of transport cause air pollution, these are buses, boats and motorcycles. Factories produce gasses that go into the air causing pollution. These things make people's health suffer.
Paragraph 2
One the one hand, there are many causes of air pollution. Firstly, there is the use of private cars. This can cause many breathing problems because of fumes. Furthermore, other forms of transport cause air pollution, for example buses, boats and motorcycles. In addition, Factories produce gasses that go into the air causing pollution. All in all/In summary, these things make people's health suffer.

Monday, August 11, 2008

How to write a research proposal

There is no single format for research proposals. This is because every research project is different. Different disciplines, donor organisations and academic institutions all have different formats and requirements. There are, however, several key components which must be included in every research proposal.

Key components are:
• A description of the research problem.
• An argument as to why that problem is important.
• A review of literature relevant to the research problem.
• A description of the proposed research methodology.
• A description of how the research findings will be used and/or disseminated.

DESCRIBING A RESEARCH PROBLEM
Before your proposal can make sense to a reader, he or she must understand clearly what the proposed research will be about. Therefore, you would do well to begin this section with a clear and simple formulation of your research question.

WHY THE RESEARCH IS IMPORTANT
This section, often referred to as the "rationale" is crucial, because it is one place in which the researcher tries to convince her/his supervisor/external examiner that the research is worth doing. You can do this by describing how the results may be used.Are there other contributions your research will make?

Literature review
The literature review presents one of the greatest challenges of the research proposal to experienced and inexperienced researchers alike.

The literature review:
* Provides a conceptual framework for the reader so that the research question and methodology can be better understood.
* Demonstrates to the expert reader that the researcher is aware of the breadth and diversity of literature that relates to the research question.

It is important that you are able to provide an integrated overview of your field of study. This means that you show awareness of the most important and relevant theories, models, studies and methodologies.

Sunday, August 10, 2008

Nokia Secret Codes

In any Nokia:
*#06# for checking the IMEI (International Mobile Equipment Identity).
*#0000# To view software version.
*#92702689# - takes you to a secret menu where you may find some of the information below:
1. Displays Serial Number.
2. Displays the Month and Year of Manufacture
3. Displays (if there) the date where the phone was purchased (MMYY)
4. Displays the date of the last repair - if found (0000)
5. Shows life timer of phone (time passes since last start)

Other:
*#7780# reset to factory settings.
*#2820# Bluetooth device address.

Download BitTorrent from Your Mobile [Symbian OS]

Now a days most people are using bit torrent. Here is a open source bit torrent client that works exactly the same way as your desktop client does.SymTorrent is the first full-featured and complete BitTorrent client for Symbian OS. It supports downloading multiple torrent files at the same time, is capable of both downloading and uploading and can save the status of your unfinished torrents, so you can resume the downloads after restarting the application. You can also check the status of each file inside a torrent along with several other statistics and properties during download.

Download

A Simple example of PIM in J2ME application [Source Code]

import java.util.Enumeration;
import javax.microedition.pim.*;

public class PIMRunner extends Thread {
private PIMTest midlet;

public PIMRunner(PIMTest midlet) {
this.midlet = midlet;
}

public void run() {
try {
ContactList addressbook = (ContactList) (PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY));
Contact contact = null;
Enumeration items = addressbook.items();
while (items.hasMoreElements()) {
contact = (Contact) (items.nextElement());
String nm[] = contact.getStringArray(Contact.NAME, 0);
if (nm[0] != null)
midlet.addMsg("Name:" + nm[0]);
else
midlet.addMsg("Name:" + nm[1]);

int count = contact.countValues(Contact.TEL);
for (int i = 0; i < count; i++) {
String tnum = contact.getString(Contact.TEL, i);
midlet.addMsg("Telephone:" + tnum );
}
midlet.addMsg("\n");
}
} catch (Exception e) {
midlet.addMsg(e.getMessage());
e.printStackTrace();
}
}

}

Thursday, August 7, 2008

IELTS Writing Tips

1. 'Stretching' your sentences makes them harder to read, less easy to grasp your point, and can also have a bad impact on your grammar. If you don't really know how to use the words you are using, the quality of your sentences will decl5. 'Stretching' your sentences makes them harder to read, less easy to grasp your point, and can also have a bad impact on your grammar. If you don't really know how to use the words you are using, the quality of your sentences will decline, as will your score. ine, as will your score.

2. Try to join sentence using words like 'although'. Long sentences (correctly written with correct grammar) have a tendency to flow better and engage the reader.

3.However, don't show off. See the IELTS Test as a test of what you can do, not a test of what you know. Some students see the writing test as a opportunity to show an assessor that they know long and complicated words, without fully understanding their meaning, and know complicated grammar structures, without really understanding how the grammar works. Do this and your score WILL go down. Do you best, but never try to go beyond what you can do - it just won't work!

4.In Task 1 your job is to put numerical information or some form of illustration into written form. The first paragraph should say what the information is. After that, think of the task in this way: write in a way that someone who can't see the table, graph, illustration, etc. would be able to draw the important points of what you are looking at.

5.In Task 2, you are often asked to give an opinion, or solve a problem in some way. Your opinion with 'support' (evidence your opinion is valid) is useless. Always give as many examples as you can that support your view.

6.Before you start writing, plan what you are going to write (but only for a maximum of 4-5 minutes).
Always write these notes in an abbreviated form (short notes); don't waste time writing sentences. It will save your time.

7.Although you can use your own experience to answer a question, never do so to the extent that you change the question. For example, you might get a question:
"Traffic problems are the chief source of global pollution. Suggest a possible solution to this problem."

Wednesday, August 6, 2008

Table growth per month in oracle 10g

The follwoing query gives the changes of each table per day in kilobytes.


SELECT DO.OBJECT_NAME,TO_CHAR(DHS.BEGIN_INTERVAL_TIME,'MM-YYYY') MONTH,
SUM(DHSS.SPACE_USED_DELTA)/1024 KB FROM
DBA_HIST_SNAPSHOT DHS,
DBA_HIST_SEG_STAT DHSS,
V$SEGMENT_STATISTICS SS,
DBA_OBJECTS DO
WHERE DHS.SNAP_ID = DHSS.SNAP_ID
AND SS.OBJ# = DHSS.OBJ#
AND DO.OBJECT_NAME=SS.OBJECT_NAME
AND SS.OBJECT_TYPE='TABLE'
AND DO.OWNER='PROD'
GROUP BY DO.OBJECT_NAME,TO_CHAR(DHS.BEGIN_INTERVAL_TIME,'MM-YYYY')
ORDER BY DO.OBJECT_NAME,TO_CHAR(DHS.BEGIN_INTERVAL_TIME,'MM-YYYY');

Bigger TextField in J2ME application [Source Code]

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

public class TextFieldTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private TextField text1;

public void startApp() {
display=Display.getDisplay(this);
form=new Form("");
text1=new TextField("","",50,TextField.ANY);
text1.setPreferredSize(100,200);
form.append(text1);
exitCommand=new Command("Exit",Command.EXIT,0);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}

protected void pauseApp() {
}

protected void destroyApp(boolean arg0) {
}

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}

}

Use of POST Method to HTTP Server in J2ME application

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HttpPostTest extends MIDlet implements CommandListener,Runnable {
private Display display;
private Form form;
private Command exitCommand;
private Command postCommand;
private TextField text1;

public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
text1 = new TextField("Name:", "", 50, TextField.ANY);
form.append(text1);
exitCommand = new Command("Exit", Command.EXIT, 0);
postCommand = new Command("Post", Command.SCREEN, 0);
form.addCommand(exitCommand);
form.addCommand(postCommand);
form.setCommandListener(this);
display.setCurrent(form);
}

protected void pauseApp() {
}

protected void destroyApp(boolean arg0) {
}

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == postCommand) {
Thread t=new Thread(this);
t.start();
}
}

public void run(){
try{
httpPost();
}catch(IOException e){
showAlert(e.getMessage());
}
}

private void showAlert(String s) {
Alert a = new Alert("Exception", s, null, null);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a, form);
}

public void httpPost() throws IOException {
HttpConnection http = null;
OutputStream oStrm = null;
InputStream iStrm = null;
String url = "http://127.0.0.1:4040/posttest.php";
try {
http = (HttpConnection) Connector.open(url);
oStrm = http.openOutputStream();
System.out.println("outputstream opened");
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// If you experience connection/IO problems, try
// removing the comment from the following line
// http.setRequestProperty("Connection", "close");

byte data[] = ("name=" + text1.getString()).getBytes();
oStrm.write(data);
System.out.println("written");
//iStrm = http.openInputStream();
System.out.println("input stream opened");
int respCode = http.getResponseCode();
if (respCode == http.HTTP_OK) {
StringBuffer sb = new StringBuffer();
iStrm = http.openDataInputStream();
int chr;
while ((chr = iStrm.read()) != -1)
sb.append((char) chr);
System.out.println(sb.toString());
showAlert(sb.toString());
}
} finally {
if (iStrm != null)
iStrm.close();
if (oStrm != null)
oStrm.close();
if (http != null)
http.close();
}
}
}

PHP CODE:
< ? PHP
$name=$_POST['name'];
print "Wellcome ".$name;
?>

Use GET Method to communicate with a HTTP Server from J2ME application

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HttpGetTest extends MIDlet {
private Display display;

public HttpGetTest() {
try {
getBirthdayFromNameUsingGet();
}
catch (IOException e) {
System.out.println("IOException " + e.toString());
}
}
public void startApp() {
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void getBirthdayFromNameUsingGet() throws IOException {

HttpConnection httpConn = null;
String url = "http://127.0.0.1/dbtest.php?user_name=sadat&password=sadat&prov_code=A";
//String url="http://www.google.com.bd/";

InputStream is = null;
OutputStream os = null;

try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);

// Setup HTTP Request
httpConn.setRequestMethod(HttpConnection.GET);
httpConn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");

/** Initiate connection and check for the response code. If the
response code is HTTP_OK then get the content from the target
**/
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK) {
StringBuffer sb = new StringBuffer();
os = httpConn.openOutputStream();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
// Web Server just returns the birthday in mm/dd/yy format.
System.out.println( sb.toString());
}
else {
System.out.println("Error in opening HTTP Connection. Error#" + respCode);
}

} finally {
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}
}
}

Tuesday, August 5, 2008

Use of RadioButton / ChoiceGroup in J2ME application

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

public class RadioButtonTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private ChoiceGroup movies;
private Command process;

public void startApp() {
display = Display.getDisplay(this);

form = new Form("");
movies = new ChoiceGroup("Select Movies You Like to See", Choice.EXCLUSIVE);
movies.append("A", null);
movies.append("B", null);
form.append(movies);
process = new Command("Process", Command.SCREEN, 2);
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.addCommand(process);
form.setCommandListener(this);
display.setCurrent(form);
}

protected void pauseApp() {
}

protected void destroyApp(boolean arg0) {
}

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == process) {
form.append(new StringItem("", movies.getSelectedIndex()==0?"true":"false" ));
}
}
}

Use CheckBox / ChoiceGroup in j2ME application

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class CheckBoxTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private ChoiceGroup movies;
private Command process;

public void startApp() {
display = Display.getDisplay(this);

form = new Form("");
movies = new ChoiceGroup("Select Movies You Like to See", Choice.MULTIPLE);
movies.append("A", null);
movies.append("B", null);
form.append(movies);
process = new Command("Process", Command.SCREEN, 2);
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.addCommand(process);
form.setCommandListener(this);
display.setCurrent(form);
}

protected void pauseApp() {
}

protected void destroyApp(boolean arg0) {
}

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == process) {
boolean picks[] = new boolean[movies.size()];
StringItem message[] = new StringItem[movies.size()];
movies.getSelectedFlags(picks);
for (int i = 0; i < picks.length; i++) {
if (picks[i]) {
message[i] = new StringItem("", movies.getString(i) + "\n");
form.append(message[i]);
}
}
}
}
}

Memory Information of JVM in mobile device [Source Code]

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

public class MemoryInformation extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;

public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.setCommandListener(this);

Runtime rtime = Runtime.getRuntime();
form.append("Total memory: " + rtime.totalMemory());
form.append("Free memory: " + rtime.freeMemory());
System.out.println("Total memory: " + rtime.totalMemory());
System.out.println("Free memory: " + rtime.freeMemory());
display.setCurrent(form);
}

protected void pauseApp() {
}

protected void destroyApp(boolean arg0) {
}

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}

Display information of Mobile Devices in J2ME application [Source Code]

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class MobileProperties extends MIDlet implements CommandListener {

private Display display;
protected boolean started;
private Command exitCommand;

protected void startApp() {
if (!started) {
display = Display.getDisplay(this);
Canvas canvas = new DummyCanvas();

Form form = new Form("Attributes");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);

boolean isColor = display.isColor();
form.append(new StringItem(isColor ? "Colors: " : "Grays: ", String.valueOf(display.numColors())));
form.append(new StringItem("Width: ", String.valueOf(canvas.getWidth())));
form.append(new StringItem("Height: ", String.valueOf(canvas.getHeight())));
form.append(new StringItem("Pointer? ", String.valueOf(canvas.hasPointerEvents())));
form.append(new StringItem("Motion? ", String.valueOf(canvas.hasPointerMotionEvents())));
form.append(new StringItem("Repeat? ", String.valueOf(canvas.hasRepeatEvents())));
form.append(new StringItem("Buffered? ", String.valueOf(canvas.isDoubleBuffered())));

form.setCommandListener(this);
display.setCurrent(form);

started = true;
}
}

protected void pauseApp() {
}

protected void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
notifyDestroyed();
}
}
}

class DummyCanvas extends Canvas {
protected void paint(Graphics g) {
}
}

Calendar in J2ME application [Source Code]

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
import java.util.Calendar;
import java.util.Date;

public class CalendarMIDlet extends MIDlet implements CommandListener {

private Display display;
private Form form;
private Command exitCommand;

public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);

Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("Day is " + day + ", month is " + month);

final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
long offset = date.getTime();
offset += 20 * MILLIS_PER_DAY;
date.setTime(offset);
cal.setTime(date);

month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("In 20 days time, day will " + day + ", month will be " + month);
System.out.println(cal);
}

protected void pauseApp() {
}

protected void destroyApp(boolean arg0) {
}

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}

Print today's Date in j2ME application [Source Code]

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import java.util.Date;

public class DateTest extends MIDlet implements CommandListener {
private Display display;
private Form form = new Form("Today's Date");
private Date today = new Date(System.currentTimeMillis());
private Command exit = new Command("Exit", Command.EXIT, 1);
private DateField datefield = new DateField("", DateField.DATE_TIME);

public DateTest() {
display = Display.getDisplay(this);
datefield.setDate(today);
form.append(datefield);
form.addCommand(exit);
form.setCommandListener(this);
}

public void startApp() {
display.setCurrent(form);
}

public void pauseApp() { }

public void destroyApp(boolean unconditional) { }

public void commandAction(Command command, Displayable displayable) {
if (command == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}

Play Tone while showing Alert in J2ME application [Source Code]

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

public class AlertSound extends MIDlet implements CommandListener {
private Display display;
private Command cmdExit;
private Command info;
private Command confirmation;
private Command warning;
private Command alarm;
private Command error;
private Form form;

public void startApp() {
display = Display.getDisplay(this);
form = new Form("Alert Tone");
cmdExit = new Command("Exit", Command.EXIT, 0);
form.addCommand(cmdExit);
info = new Command("Information", Command.SCREEN, 0);
form.addCommand(info);
confirmation = new Command("Confirmation", Command.SCREEN, 0);
form.addCommand(confirmation);
warning = new Command("Warning", Command.SCREEN, 0);
form.addCommand(warning);
alarm = new Command("Alarm", Command.SCREEN, 0);
form.addCommand(alarm);
error = new Command("Error", Command.SCREEN, 0);
form.addCommand(error);
form.setCommandListener(this);
display.setCurrent(form);
}

protected void pauseApp() {
}

protected void destroyApp(boolean arg0) {
}

public void commandAction(Command c, Displayable s) {
if (c == info)
AlertType.INFO.playSound(display);
else if (c == confirmation)
AlertType.CONFIRMATION.playSound(display);
else if (c == warning)
AlertType.WARNING.playSound(display);
else if (c == alarm)
AlertType.ALARM.playSound(display);
else if (c == error)
AlertType.ERROR.playSound(display);
else if (c == cmdExit) {
destroyApp(true);
notifyDestroyed();
}
}
}

Supported Media fies and protocols in mobile [Source Code]

We can check which file can be shown, played or which protocols are supported in mobile device from  J2ME application. Or it can be used whether mp3 files can be run from mobile or NOT.

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;

public class MediaInformation extends MIDlet implements CommandListener {
private Form mInformationForm;

public void startApp() {
if (mInformationForm == null) {
mInformationForm = new Form("Content types and protocols");
String[] contentTypes = Manager.getSupportedContentTypes(null);
for (int i = 0; i < contentTypes.length; i++) {
String[] protocols = Manager.getSupportedProtocols(contentTypes[i]);
for (int j = 0; j < protocols.length; j++) {
StringItem si = new StringItem(contentTypes[i] + ": ", protocols[j]);
//si.setLayout(Item.LAYOUT_NEWLINE_AFTER);
mInformationForm.append(si);
}
}
Command exitCommand = new Command("Exit", Command.EXIT, 0);
mInformationForm.addCommand(exitCommand);
mInformationForm.setCommandListener(this);
}

Display.getDisplay(this).setCurrent(mInformationForm);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
}

Play audio/mp3 file from J2ME application [Source Code]

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;

public class PlayAudio extends MIDlet implements CommandListener, Runnable {
private Display mDisplay;
private List mMainScreen;
public void startApp() {
mDisplay = Display.getDisplay(this);
if (mMainScreen == null) {
mMainScreen = new List("AudioMIDlet", List.IMPLICIT);
mMainScreen.append("From resource", null);
mMainScreen.addCommand(new Command("Exit", Command.EXIT, 0));
mMainScreen.addCommand(new Command("Play", Command.SCREEN, 0));
mMainScreen.setCommandListener(this);
}

mDisplay.setCurrent(mMainScreen);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) notifyDestroyed();
else {
Form waitForm = new Form("Loading...");
mDisplay.setCurrent(waitForm);
Thread t = new Thread(this);
t.start();
}
}

public void run() {
playFromResource();
}
private void playFromResource() {
try {
InputStream is = getClass().getResourceAsStream("/home/sadat/wohlamhe.mp3");
Player player = Manager.createPlayer(is,"audio/mpeg"); 
player.start();
}
catch (Exception e) {
showException(e);
return;
}
mDisplay.setCurrent(mMainScreen);
}
private void showException(Exception e) {
Alert a = new Alert("Exception", e.toString(), null, null);
a.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(a, mMainScreen);
}
}

Monday, August 4, 2008

Using Interactive Gause in J2ME application [Source Code]

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Timer;
import java.util.TimerTask;

public class GaugeExample extends MIDlet implements CommandListener{
private Display display;
private Form fmMain;
private Command cmExit;
private Command cmStop;
private Gauge gaProgress;
private Timer tm;
private GuageTimerTask tt;

public GaugeExample() {
display = Display.getDisplay(this);

gaProgress = new Gauge("Gauge Progress", false, 20, 1);
cmExit = new Command("Exit", Command.EXIT, 1);
cmStop = new Command("Stop", Command.STOP, 1);

fmMain = new Form("");
fmMain.append(gaProgress);
fmMain.addCommand(cmStop);
fmMain.setCommandListener(this);
}

public void startApp() {
display.setCurrent(fmMain);
tm = new Timer();
tt = new GuageTimerTask();
tm.scheduleAtFixedRate(tt, 0, 500);
}

public void pauseApp(){ }

public void destroyApp(boolean unconditional) { }

public void commandAction(Command c, Displayable s) {
if (c == cmExit){
destroyApp(false);
notifyDestroyed();
}else if (c == cmStop){
tm.cancel();
fmMain.removeCommand(cmStop);
fmMain.addCommand(cmExit);
gaProgress.setLabel("Progress Cancelled!");
}
}

/*--------------------------------------------------
* Inner Class
*-------------------------------------------------*/
private class GuageTimerTask extends TimerTask {
public final void run() {
if (gaProgress.getValue() < gaProgress.getMaxValue())
gaProgress.setValue(gaProgress.getValue() + 1);
else {
fmMain.removeCommand(cmStop);
fmMain.addCommand(cmExit);
gaProgress.setLabel("Guage Complete!");
cancel();
}
}
}
}

Fetch Image From PHP Server in J2ME application [Source Code]

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class ImageFetch extends MIDlet implements CommandListener{
private Display display;
private String URL = "http://127.0.0.1:4040/j2me.php";
private Form formImage;
private Command cmdExit;

public ImageFetch() {
try {
display = Display.getDisplay(this);
cmdExit=new Command("Exit",Command.EXIT,0);
Image im = getImage(URL);
formImage = new Form("Simple Image Test");
formImage.append(im);
formImage.addCommand(cmdExit);
formImage.setCommandListener(this);
display.setCurrent(formImage);
} catch (Exception ex) {
System.out.println(ex);
}
}

public void commandAction(Command c, Displayable s) {
destroyApp(true);
notifyDestroyed();
}
public void startApp() {
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

private Image getImage(String url) throws IOException {
ContentConnection connection = (ContentConnection) Connector.open(url);
DataInputStream iStrm = connection.openDataInputStream();
Image im = null;

try {
byte imageData[];
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
imageData = bStrm.toByteArray();
bStrm.close();
im = Image.createImage(imageData, 0, imageData.length);
} finally {
if (iStrm != null)
iStrm.close();
if (connection != null)
connection.close();
}
return (im == null ? null : im);
}
}


PHP CODE
< ?
$filename = "./passport.jpg";
$handle = fopen ($filename, "rb");
$contents = fread ($handle, filesize ($filename));
fclose ($handle);
echo $contents
?>

Use Timer from J2ME application [Source Code]

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

public class TimerMIDlet extends MIDlet implements CommandListener{
private Display display;
private Form form;
private Command exit;
private Command stop;
private Timer timer;
private RunTimerTask tt;
private int count = 0;

public TimerMIDlet(){
form = new Form("Timer");
exit = new Command("Exit", Command.EXIT, 1);
stop= new Command("Stop", Command.STOP, 2);
}

public void startApp (){
display = Display.getDisplay(this);
form.addCommand(exit);
form.addCommand(stop);
form.setCommandListener(this);

// Repeating every 3 seconds
timer = new Timer();
tt = new RunTimerTask();
timer.schedule(tt,0, 3000);
display.setCurrent(form);
}

public void destroyApp (boolean unconditional){}

public void pauseApp () { }

public void commandAction(Command c, Displayable d){
if (c == stop){
timer.cancel();
}
else if (c == exit){
destroyApp(false);
notifyDestroyed();
}
}

/*--------------------------------------------------
* RunTimerTask Class - Run the task-Inner Class
*-------------------------------------------------*/
private class RunTimerTask extends TimerTask{
public final void run(){
form.append("count: " + ++count + "\n");
}
}
}

Vibrate your phone with J2ME application

You can vibrate your phone by simply using the code,
Display.getDisplay(this).vibrate(800);

Boot DOS from Flash Drive Without Using Floppy Drive

Step 1:
Download the files:
1.http://www.docjelly.com/Blog/content/binary/SP27213.exe
2.http://chitchat.at.infoseek.co.jp/vm...d21-050404.zip
3.http://www.msu-hb.de/download/boot98se.exe
Step 2:
Install the SP27213.exe file. If you need to use a floppydisk image file to access the DOS system files, extract the vfd21-050404.zip somewhere ( say c:\utility\VFD\ ).If you are using the floppydisk image file, extract the boot98.exe file using a WinRar. This archive will give you an error when extracted with winrar, but the image file inside (winb98.ima) will be extracted. Put the resulting winb98.ima file somewhere ( say c:\utility\VFD\ ), this step is needed only if you have no other source for the DOS system files.

Step 3:
Insert the USB Memory Device, do not use a HUB.Run the VFD Control Panel (c:\utility\VFD\vfdwin.exe).The VFD Control Panel will start on the device driver tab, press the [install] and [start] buttons. Switch to the drive 0 tab, and press the [drive letter] button, and select something other than your drive letter.Now, you will press the [open] button, and point the VFD Control Panel to either the WINB98.IMA image file and click the new [open] button.
Start the HP USB Disk Storage Format Tool (from the start menu).Select FAT or FAT32 as your file system, Fat32 may be preferable for large memory devices.
Optionally, you may give your USB-MD a Volume Label.
Click the Quick Format check box.
Click the Create DOS Startup Disk check box.
Select the Using DOS System Files Located at: radio button.
Point the HP Utility to the source of your DOS system files (the directory, floppy, or virtual floppy drive) using the [...] button below the Using DOS System Files Located at: radio button.
Click the [Start] button.

Lastly:
Go to the VFD Control Panel and on the drive 0 tab, press the [close] button, next go the the driver tab and press the [stop] and [uninstall] button, and exit the VFD Control Panel.

Your computer SHOULD now boot from the USB Memory Device.

search engine

Custom Search