This Part 3 will consist of Networking, ListField, JSON and Thread.
I'm really sorry for pending this part 3. I've been busy making money and still failed. Its just really hard to live in third world country by coding.
anyway, There are few Library that you will need creating ListField with JSON data, but we wont touch that area first. we need to learn the basic.
* note added : Aug 26 2013
The basic should be :
Simple HttpConnection
I'm Using HttpConnection to create connection to web server. This is simple HttpConnection code
This is TestNetworkScreen.java
This Code is really crappy. the private function appendConnectionString and getCarrierBIBSUid is just code that i copied from another resource. already forget where i got it.
The result of the code is just create button that request to http://www.google.com then get the result from it. this is the result image
when you click the button it shows the html code.
that is just some simple code to start a spark on my brain that will create storm to complete this tutorial.
Simple ListField and JSON
i will create listfield that generate data from json string, its not yet using network and thread but at least its working.
you will need json library from json.org. I'm using https://github.com/upictec/org.json.me
anyway this is the listfield code with getCategory method to convert json string into array.
MenuCategoryListField.java
to show it on screen just use this code
this is the result
I'm really sorry for the late update. since i don't have any job so i dont have any internet connection.
[its not done yet. i will add more code later. i need to sleep]
I'm really sorry for pending this part 3. I've been busy making money and still failed. Its just really hard to live in third world country by coding.
anyway, There are few Library that you will need creating ListField with JSON data, but we wont touch that area first. we need to learn the basic.
* note added : Aug 26 2013
The basic should be :
- Networking
- Thread
- ListField
- [if i find anything, will be add here]
Simple HttpConnection
I'm Using HttpConnection to create connection to web server. This is simple HttpConnection code
This is TestNetworkScreen.java
import java.io.IOException; import java.io.InputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import net.rim.device.api.servicebook.ServiceBook; import net.rim.device.api.servicebook.ServiceRecord; import net.rim.device.api.system.CoverageInfo; import net.rim.device.api.system.DeviceInfo; import net.rim.device.api.system.WLANInfo; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.FieldChangeListener; import net.rim.device.api.ui.component.ButtonField; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.container.MainScreen; /** * A class extending the MainScreen class, which provides default standard * behavior for BlackBerry GUI applications. */ public final class TestNetworkScreen extends MainScreen { LabelField StatusField; /** * Creates a new TestNetworkScreen object */ public TestNetworkScreen() { // Set the displayed title of the screen setTitle("Test Network"); ButtonField myButton = new ButtonField("Ping Google",ButtonField.CONSUME_CLICK|FIELD_HCENTER); StatusField = new LabelField(); FieldChangeListener myListener = new FieldChangeListener() { public void fieldChanged(Field field, int context) { // TODO Auto-generated method stub final WaitScreen myWait = new WaitScreen("Please Wait"); try { HttpConnection conn = null; conn = (HttpConnection)Connector.open("http://www.google.com/" + appendConnectionString()); conn.setRequestMethod(HttpConnection.POST); conn.getHeaderField("Content-type"); InputStream input = conn.openInputStream(); byte[] data = new byte[256]; int len = 0; StringBuffer raw = new StringBuffer(); while(-1 != (len = input.read(data))) { raw.append(new String(data,0,len)); } String result = raw.toString(); conn.close(); StatusField.setText(result); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); StatusField.setText("FAILED"); } } }; myButton.setChangeListener(myListener); add(myButton); add(StatusField); } private static String appendConnectionString() { // This code is based on the connection code developed by Mike Nelson of AccelGolf. // http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection String connectionString = null; // Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR variable. if(DeviceInfo.isSimulator()) { connectionString = ";deviceside=true"; //if(UploaderThread.USE_MDS_IN_SIMULATOR) //{ //this.labelText.setText("Device is a simulator and USE_MDS_IN_SIMULATOR is true"); //connectionString = ";deviceside=false"; //} //else //{ //logMessage("Device is a simulator and USE_MDS_IN_SIMULATOR is false"); //connectionString = ";deviceside=true"; //} } // Wifi is the preferred transmission method else if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) { //logMessage("Device is connected via Wifi."); connectionString = ";interface=wifi"; } // Is the carrier network the only way to connect? else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) { //logMessage("Carrier coverage."); String carrierUid = getCarrierBIBSUid(); if(carrierUid == null) { // Has carrier coverage, but not BIBS. So use the carrier's TCP network //logMessage("No Uid"); connectionString = ";deviceside=true"; } else { // otherwise, use the Uid to construct a valid carrier BIBS request // logMessage("uid is: " + carrierUid); connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public"; } } // Check for an MDS connection instead (BlackBerry Enterprise Server) else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) { //logMessage("MDS coverage found"); connectionString = ";deviceside=false"; } // If there is no connection available abort to avoid bugging the user unnecssarily. else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) { //logMessage("There is no available connection."); } // In theory, all bases are covered so this shouldn't be reachable. else { //logMessage("no other options found, assuming device."); connectionString = ";deviceside=true"; } return ";ConnectionTimeout=20000" + connectionString; } private static String getCarrierBIBSUid() { ServiceRecord[] records = ServiceBook.getSB().getRecords(); int currentRecord; for(currentRecord = 0; currentRecord < records.length; currentRecord++) { if(records[currentRecord].getCid().toLowerCase().equals("ippp")) { if(records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) { return records[currentRecord].getUid(); } } } return null; } }
This Code is really crappy. the private function appendConnectionString and getCarrierBIBSUid is just code that i copied from another resource. already forget where i got it.
The result of the code is just create button that request to http://www.google.com then get the result from it. this is the result image
when you click the button it shows the html code.
that is just some simple code to start a spark on my brain that will create storm to complete this tutorial.
Simple ListField and JSON
i will create listfield that generate data from json string, its not yet using network and thread but at least its working.
you will need json library from json.org. I'm using https://github.com/upictec/org.json.me
anyway this is the listfield code with getCategory method to convert json string into array.
MenuCategoryListField.java
import java.util.Vector; import json.me.JSONArray; import json.me.JSONException; import json.me.JSONObject; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.DrawStyle; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Font; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.ListField; import net.rim.device.api.ui.component.ListFieldCallback; public class MenuCategoryListField extends ListField implements ListFieldCallback{ private Font font; Vector rows,blows; JSONArray lists; TableRowManager row; Bitmap myImage = Bitmap.getBitmapResource("chevron_right_black_15x22.png"); public JSONArray getCategory (){ // this function is not using any httpRequest JSONArray lists = null; //String result = httpRequest(mySite + "index.php/service/Findallkfckategori"); String result = "[{\"id\":\"1\",\"name\":\"Favorit\",\"description\":\"Menu-menu favorit\",\"picture\":\"Favorit.jpg\",\"active\":\"1\",\"sort_number\":\"3\"}" + ",{\"id\":\"2\",\"name\":\"Praktis\",\"description\":\"Menu Praktis KFC\",\"picture\":\"Praktis-thumb.jpg\",\"active\":\"1\",\"sort_number\":\"2\"}" + ",{\"id\":\"3\",\"name\":\"Ala Carte\",\"description\":\"Menu-menu Ala Carte\",\"picture\":\"Ala%20Carte-thumb.jpg\",\"active\":\"1\",\"sort_number\":\"4\"}" + ",{\"id\":\"4\",\"name\":\"Chiaki\",\"description\":\"Menu Chiaki KFC\",\"picture\":\"Kids%20meal-thumb.jpg\",\"active\":\"1\",\"sort_number\":\"2\"}" + ",{\"id\":\"5\",\"name\":\"Music\",\"description\":\"Menu Music KFC\",\"picture\":\"Music-thumb.jpg\",\"active\":\"1\",\"sort_number\":\"1\"}]"; try { lists = new JSONArray(result); } catch (JSONException ex) { // TODO Auto-generated catch block //Dialog.inform(ex.getMessage()); } return lists; } public MenuCategoryListField() { super(0, ListField.MULTI_SELECT); setEmptyString("* No Menu *!!",DrawStyle.HCENTER); setCallback(this); setRowHeight(50); font = Font.getDefault(); lists = this.getCategory(); if(lists != null) { rows = new Vector(); blows = new Vector(); for(int x = 0; x < lists.length(); ++x) { JSONObject list; try { list = lists.getJSONObject(x); row = new TableRowManager(); row.add(new LabelField(list.getString("name"), DrawStyle.ELLIPSIS)); row.add(new FontColorField("", DrawStyle.ELLIPSIS | Field.USE_ALL_WIDTH | DrawStyle.RIGHT, 0x00878787, font)); rows.addElement(row); blows.addElement(list.getString("id")); } catch (JSONException e) { // TODO Auto-generated catch block //e.printStackTrace(); //Dialog.inform("Listing False"); } } setSize(rows.size()); } else { setEmptyString("* Couldn't Connect To Server *!!",DrawStyle.HCENTER); } } public void drawListRow(ListField listField, Graphics g, int index, int y, int width) { MenuCategoryListField list = (MenuCategoryListField) listField; TableRowManager rowManager = (TableRowManager)list.rows.elementAt(index); rowManager.drawRow(g, 0, y, width, list.getRowHeight()); } public Object get(ListField list, int index) { JSONObject mylist; try { mylist = lists.getJSONObject(index); return mylist.getString("name"); } catch (JSONException e) { // TODO Auto-generated catch block //e.printStackTrace(); return null; } } public int indexOfList(ListField list, String p, int s) { return -1; } public int getPreferredWidth(ListField list) { return Graphics.getScreenWidth(); } protected boolean trackwheelClick(int status, int time) { final int index = getSelectedIndex(); UiApplication.getUiApplication().invokeAndWait(new Runnable() { public void run() { //Dialog.inform(blows.elementAt(index).toString()); int myIdCategory = Integer.parseInt(blows.elementAt(index).toString()); //UiApplication.getUiApplication().pushScreen(new TaskListScreen(rtm, lists[index].getName(), rtm.getTasksByList(lists[index].getListID()))); //new MenuController(myIdCategory); } }); return true; } private class TableRowManager extends Manager { public TableRowManager(){ super(0); } public void drawRow(Graphics g, int x, int y, int width, int height){ // Arrange the cell fields within this row manager. layout(width, height); // Place this row manager within its enclosing list. setPosition(x, y); // Apply a translating/clipping transformation to the graphics // context so that this row paints in the right area. g.pushRegion(getExtent()); // Paint this manager's controlled fields. subpaint(g); g.setColor(0xFF0000); g.drawLine(0, height-1, getPreferredWidth(), height-1); g.drawBitmap(getPreferredWidth() - 30, (height - myImage.getHeight()) / 2 , myImage.getWidth(), myImage.getHeight(), myImage, 0, 0); // Restore the graphics context. g.popContext(); } protected void sublayout(int width, int height) { // TODO Auto-generated method stub int preferredWidth = getPreferredWidth(); int preferredHeight = getPreferredHeight(); Field field = getField(0); Font myFont = field.getFont(); int myHeight = myFont.getHeight() / 2; layoutChild(field, preferredWidth - 110, preferredHeight); setPositionChild(field, 15, preferredHeight / 2 - myHeight); field = getField(1); layoutChild(field, 75, preferredHeight); setPositionChild(field, preferredWidth-75, 0); setExtent(preferredWidth, preferredHeight); } public int getPreferredWidth() { return Graphics.getScreenWidth(); } // The preferred height of a row is the "row height" as defined in the // enclosing list. public int getPreferredHeight() { return getRowHeight(); } } }
to show it on screen just use this code
MenuCategoryListField myList = new MenuCategoryListField(); add(myList);
this is the result
I'm really sorry for the late update. since i don't have any job so i dont have any internet connection.
[its not done yet. i will add more code later. i need to sleep]
Comments