Tuesday, December 25, 2012

BlackBerry SQLITE databse example with CURD Operations

1)Create a project with name DataBaseExample

and insert the code inside MyScreen.java


package mypackage;

import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.MainScreen;

public final class MyScreen extends MainScreen {

public static final String uripath = "file:///SDCard/Databases/example/"
+ "DemoApp.db";

public MyScreen() {

setTitle("Database Example");
DatabaseSupporter dboperation = new DatabaseSupporter();
dboperation.createDataBaseApp(uripath);
add(new LabelField("database created"));
add(new SeparatorField());
dboperation.createDataBaseTable(uripath);
add(new LabelField("database table created"));
add(new SeparatorField());
dboperation.insertintoDataBaseTable(uripath);
add(new LabelField("database value inserted"));
add(new SeparatorField());
String temp = dboperation.retrievefromoDataBaseTable(uripath);
add(new LabelField("database retrieved==" + temp));
add(new SeparatorField());
//dboperation.updateDataBaseTable(uripath);
//dboperation.deleteDatabase(uripath);
}
}





2) now make new java class for CURD operations as DatabaseSupporter.java and copy following code to it



package mypackage;

import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Row;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;

public class DatabaseSupporter {
Database d;

public DatabaseSupporter() {
}

public void createDataBaseApp(String uripath) {

try {
URI myURI = URI.create(uripath);
if (DatabaseFactory.exists(myURI) == true) {
// nothing to do if ALREADY exists
} else {
d = DatabaseFactory.create(myURI);
d.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}

public void createDataBaseTable(String uripath) {
try {
URI myURI = URI.create(uripath);
d = DatabaseFactory.open(myURI);
Statement st_todelete = d
.createStatement("DROP TABLE if exists People");
st_todelete.prepare();
st_todelete.execute();
st_todelete.close();
Statement st = d.createStatement("CREATE TABLE 'People' ( "
+ "'Name' TEXT, " + "'Age' INTEGER )");
st.prepare();
st.execute();
st.close();
d.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}

public void insertintoDataBaseTable(String uripath) {
try {
URI myURI = URI.create(uripath);
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("INSERT INTO People(Name,Age) "
+ "VALUES ('Jitesh',26)");
st.prepare();
st.execute();
st.close();
d.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}

public String retrievefromoDataBaseTable(String uripath) {
String stringvalue = "value inside db is==>";
try {
URI myURI = URI.create(uripath);
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT Name,Age FROM People");
st.prepare();
net.rim.device.api.database.Cursor c = st.getCursor();
Row r;
int i = 0;
while (c.next()) {
r = c.getRow();
i++;
stringvalue = stringvalue
+ (" " + i + "=> Name = " + r.getString(0) + " , "
+ "Age = " + r.getInteger(1));
}
if (i == 0) {
return "there is nothing to return";
}
st.close();
d.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return stringvalue;
}

public void updateDataBaseTable(String uripath) {
try {
d = DatabaseFactory.open(uripath);
Statement st = d.createStatement("UPDATE People SET Age=27 "
+ "WHERE Name='jitesh'");
st.prepare();
st.execute();
st.close();
d.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}

public void deleteDatabase(String uripath) {
try {
URI myURI = URI.create(uripath);
DatabaseFactory.delete(myURI);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}

}

3) run on emulator, do not forget to insert sd card, follow these steps

simulate==>change sd card=> [click on "+ folder icon" and choose the path]=> now click on "+" at right side to insert sd card and click again on the path value shown to you



Sunday, December 23, 2012

BlackBerry Deleting data in SD CARD from a given path directory


In BlackBerry we can delete all the data from a given path in SD card by using the following code method. it is help utility which we can use in our programs.

private static void deleteFolder(String fullPath) {
   try {
    FileConnection dirConn = (FileConnection)Connector.open(fullPath, Connector.READ_WRITE);
       if(dirConn.exists() && dirConn.isDirectory()) {
        for(Enumeration e = dirConn.list("*", true); e.hasMoreElements();) {
String name = e.nextElement().toString();
deleteIOneFile(fullPath + name);
}
        dirConn.delete();
       }
       dirConn.close();
} catch(IOException ioe) {
System.out.println("1 Exception : " + ioe.toString());
}
}

Where path can be like
 fullPath= "file:///SDCard/Databases/SQLite_Guide/imageshere/";

BlackBerry checking Network availability before theNetwork Interaction


Some time we need to check the availability of the network connection , with the help of this little code snippet we can check that the network is available or not, before using the the network interaction!!

public static String getTransports() {

avail = "notavailable";
_transportsWithCoverage = TransportInfo.getCoverageStatus();
_transports = TransportInfo
.getTransportDescriptors(_transportsWithCoverage);
for (int i = _transports.length - 1; i >= 0; --i) {
switch (_transports[i].getTransportType()) {
case TransportInfo.TRANSPORT_BIS_B: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_MDS: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_TCP_CELLULAR: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_TCP_WIFI: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_WAP: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_WAP2: {
avail = "available";
return avail;
}
}
}
return avail;

}

BlackBerry available connection idenitification


In BlackBerry we can identify the availability of the connection type that we can use it appropriately. just have a look on following code snipet!!

import java.rmi.ServerException;

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;

public class ConnectionCreator {

    public static String getConnectionStringMethod() throws ServerException 
    {
        String connectionString = null;                
                        
        // Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR variable.
        if(DeviceInfo.isSimulator())
        {
            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)
        {
                       
            String carrierUid = getCarrierBIBSUid();
            if(carrierUid == null) 
            {
                // Has carrier coverage, but not BIBS.  So use the carrier's TCP network
                 connectionString = ";deviceside=true";
            }
            else 
            {
                // otherwise, use the Uid to construct a valid carrier BIBS request
                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)
        {
            connectionString = ";deviceside=false";
        }
        
        // If there is no connection available abort to avoid bugging the user unnecssarily.
        else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
        {
            ServerException exception = new ServerException("No connection found");
            
            throw exception;
        }
        
        // In theory, all bases are covered so this shouldn't be reachable.
        else
        {
            connectionString = ";deviceside=true";
        }        
        
        return 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;
    }
}

BlackBerry Custom Image Button with hover effect and Button name below Image


In Blackberry we can just use a custom button where it will have all the hover effects and also the image label just below the button Image.




import java.util.Timer;
import java.util.TimerTask;

import onepoint.blackberry.gfk.utility.all.FontDetails;
import onepoint.blackberry.gfk.utility.all.ImageResigeUtility;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
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;

public class ScrollHomeButton extends Field implements DrawStyle {

private Bitmap _currentPicture;
private Bitmap _onPicture;
private Bitmap _offPicture;
private int width;
private int height;
private int text_off_sel, text_on_sel, textcolor;
private String labeldata;
private int backgroundColour;
private int highlightColour;
private int colorvalue;
FontDetails fontd;
String text;
final int screenWidth = Display.getWidth() / 3;
int offset = screenWidth;
Timer timer = new Timer();
final int delay = 30;

private int fontsize;

public void setText(String text) {
this.text = text;
}

public String getText() {
return text;
}

public ScrollHomeButton(String onImage, String offImage, String label,
int width, int height, int fontsize1, int off_sel, int on_sel,
int offcolor, int oncolor) {
super();
_offPicture = Bitmap.getBitmapResource(onImage);
_onPicture = Bitmap.getBitmapResource(offImage);
_currentPicture = _offPicture;
labeldata = label;
this.width = width;
this.height = height;
this.fontsize = fontsize1;
this.backgroundColour = off_sel;
this.highlightColour = on_sel;
this.text_off_sel = offcolor;
this.text_on_sel = oncolor;
this.colorvalue = off_sel;
textcolor = offcolor;
fontd = new FontDetails();
this.setFont(fontd.retrieveFont(fontsize));
this.text = label;
final int width_ = Font.getDefault().getAdvance(text);
TimerTask timerTask = new TimerTask() {
public void run() {
offset--;
if (offset + width_ == 0) {
offset = screenWidth;
}
invalidate();
}
};
timer.scheduleAtFixedRate(timerTask, delay, delay);
}

public int getPreferredHeight() {
return height;
}

public int getPreferredWidth() {
return width;
}

public boolean isFocusable() {
return true;
}

// Override function to switch picture
protected void onFocus(int direction) {
colorvalue = highlightColour;
_currentPicture = _onPicture;
textcolor = text_on_sel;
invalidate();
}

// Override function to switch picture
protected void onUnfocus() {
colorvalue = backgroundColour;
_currentPicture = _offPicture;
textcolor = text_off_sel;
invalidate();
}

protected void layout(int width, int height) {
setExtent(getPreferredWidth(), getPreferredHeight());
}

// update the fieldchange
protected void fieldChangeNotify(int context) {
try {
this.getChangeListener().fieldChanged(this, context);
} catch (Exception exception) {
}
}

//
protected void paint(Graphics graphics) {
graphics.clear();
graphics.setColor(colorvalue);
graphics.fillRect(0, 0, getWidth(), getHeight());
graphics.drawBitmap(
(getPreferredWidth() - _currentPicture.getWidth()) / 2,
(getPreferredHeight() - _currentPicture.getHeight()) / 8,
_currentPicture.getWidth(), _currentPicture.getHeight(),
_currentPicture, 0, 0);
graphics.setColor(Color.WHITE);
String label = labeldata;
int x = (getPreferredWidth() - getFont().getAdvance(label)) >> 1;
int y = (getPreferredHeight() - getFont().getHeight()) >> 1;
graphics.setColor(textcolor);
if (text.length() > 10) {
// graphics.setFont(fontd.retrieveFont(fontsize));
graphics.drawText(text, offset, y + getFont().getHeight() - 2);
} else {
// graphics.setFont(fontd.retrieveFont(fontsize));
graphics.drawText(label, x, y + getFont().getHeight() - 2);
}
Bitmap temp = Bitmap.getBitmapResource("menu_div.png");
ImageResigeUtility imgsrc = new ImageResigeUtility();
Bitmap div = imgsrc.createBitmap("menu_div.png", temp.getWidth(),
height);
graphics.drawBitmap(0, 0, div.getWidth() - 1, height, div, 0, 0);
graphics.drawBitmap(this.getWidth() - 1, 0, div.getWidth() - 1, height,
div, 0, 0);

}

// Listen for navigation Click
protected boolean navigationClick(int status, int time) {
fieldChangeNotify(1);
return true;
}

}

BlackBerry Ticker like LabelField


in BlackBerry we can make a Ticker like field where the text is in a moving condition. it is some times very helpful to make some customization and to achieve interactive UI in BlackBerry. we just need to make a class file with name MovingLabelField.java and copy the given below code to it.


import java.util.Timer;
import java.util.TimerTask;

import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.LabelField;

public class MovingLabelField extends LabelField{
int currentChar = 0;
String currentText = null;
Font ourFont;
private Timer _scrollTimer;
private TimerTask _scrollTimerTask;

public MovingLabelField (String text){
super(text);

}
public void paint(Graphics graphics) {
currentText = this.getText();
if (currentChar < currentText.length()) {
currentText = currentText.substring(currentChar);
}
graphics.drawText(currentText, 0, 0, DrawStyle.ELLIPSIS,
Display.getWidth());
}
protected void paintBackground(net.rim.device.api.ui.Graphics g) {
g.setColor(0x666666);
}


protected void onDisplay() {
startScroll();
}

protected void onUnfocus() {
startScroll();
}

private void startScroll() {
// Start scrolling
final String fullText = this.getText();
if (_scrollTimer == null) {
_scrollTimer = new Timer();
_scrollTimerTask = new TimerTask() {
public void run() {
currentChar = currentChar + 4;
if (currentChar > fullText.length()) {
currentChar = 0;
}
invalidate();
}
};
_scrollTimer
.scheduleAtFixedRate(_scrollTimerTask, 500, 500);
}
}

protected void onFocus(int direction) {
if (_scrollTimer != null) {
_scrollTimerTask.cancel();
_scrollTimer.cancel();
_scrollTimer = null;
_scrollTimerTask = null;
}
}

protected boolean navigationMovement(int dx, int dy, int status,
int time) {
currentText = this.getText();
int oldCurrentChar = currentChar;
if (Math.abs(dx) > Math.abs(dy)) {
// horizontal scroll
if (dx > 0) {
currentChar = Math.min(currentText.length() - 1,
currentChar + 1);
} else if (dx < 0) {
currentChar = Math.max(0, currentChar - 1);
}
if (oldCurrentChar != currentChar) {
this.invalidate();
}
return true;
} else {
return super.navigationMovement(dx, dy, status, time);
}
}
}

Thursday, December 20, 2012

BlackBerry creating a Custom TextTitlebar

We cabn make a titlebar rather than using a default one. please copy the code and you can use and customize further

TitleBarText.java




import onepoint.blackberry.gfk.utility.all.FontDetails;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;


public class TitleBarText extends Field implements DrawStyle
{
    private int fieldWidth;
    private int fieldHeight;
    private int fontColour;
    private int backgroundColor;
   
 
    private  int BACKGROUND_COLOR = 0x00000000;
    private String label;
   
   
    public TitleBarText(int height,int BACKGROUND_COLOR_,String text,int fontsize)
    {
        super(Field.NON_FOCUSABLE);
        fieldHeight =height;
        fieldWidth = Display.getWidth();
       
        //background color is black
        backgroundColor = BACKGROUND_COLOR_;
        label=text;
       
       
this.setFont(...);//set you font here for this field
    }
   
    public void setBackgroundColour(int _backgroundColour)
    {
        backgroundColor = _backgroundColour;
        invalidate();
    }
   
    protected void layout(int width, int height)
    {
        setExtent(getPreferredWidth(), getPreferredHeight());
    }
   
    public int getPreferredWidth()
    {
        return fieldWidth;
    }
   
    public int getPreferredHeight()
    {
        return fieldHeight;
    }
   
    protected void paint(Graphics graphics)
    {
       
        int w = this.getPreferredWidth();
        int h = this.getPreferredHeight();
       
        graphics.setColor(backgroundColor);
        graphics.fillRect(0, 0, w, h);
        graphics.setColor(Color.WHITE);
        graphics.drawText(label, 10, (h-getFont().getHeight())/2);
     
    }
}

BlackBerry Custom ImageButton

To achieve this we just need to write a program as follows. make a java class with name ImageButton and copy the below code to this file:


import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;

public class ImageButton extends Field {

private Bitmap _currentPicture;
private Bitmap _onPicture;
private Bitmap _offPicture;
private int id;

public ImageButton(Bitmap onImage, Bitmap offImage) {
super(Field.FIELD_HCENTER | Field.FIELD_VCENTER
| Field.HIGHLIGHT_SELECT | Field.FOCUSABLE);
_offPicture = offImage;
_onPicture = onImage;
_currentPicture = _onPicture;
}

public void setButtonId(int id) {
this.id = id;
}

public int getButtonId() {
return this.id;
}

public int getPreferredHeight() {
return _onPicture.getHeight();
}

public int getPreferredWidth() {
return _onPicture.getWidth();
}

protected void onFocus(int direction) {
_currentPicture = _offPicture;
invalidate();
}

protected void onUnfocus() {
_currentPicture = _onPicture;
invalidate();
}

protected void drawFocus(Graphics g, boolean on) {
g.setBackgroundColor(Color.WHITE);
}

protected void layout(int width, int height) {
setExtent(Math.min(width, getPreferredWidth()),
Math.min(height, getPreferredHeight()));
}

protected void paint(Graphics graphics) {

graphics.clear();
graphics.setBackgroundColor(0xe8edef);

graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0,
0);
}

protected boolean navigationClick(int status, int time) {
fieldChangeNotify(0);
return true;
}

public boolean keyChar(char key, int status, int time) {
if (key == Characters.ENTER) {
fieldChangeNotify(0);
return true;
}
return false;
}
}