Related
I have a problem when I'm trying to find a way to check if a trade was made on the current bar or not to stop the EA for making multiple entries on the same bar.
When I don't do a multi Currency EA I usually just use
static datetime lastTradeBar;
and
if(lastTradeBar!=Time[0])
{
if(PFTP_BuySignal > 0 && PFTP_BuySignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_BuySL;
return (1);
}
if(PFTP_SellSignal > 0 && PFTP_SellSignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_SellSL;
return (-1);
}
else
return (0);
lastTradeBar=Time[0];
};
return (0);
}
but this doesn't work when using it as I do now.
I'm thinking I need to make a myArray[sym,period,lastTradeBar] or myArray [sym][period][lastTradeBar]
but I can't wrap my head around how or where to put it.
this is the flow
int OnInit() ->
void OnTimer() ->
void LoopThruSym(stringlistOfSym) ->
void LoopThruPeriod(string sym, string listOfPeriods, int listOfSym) ->
void Trade(string sym, int period) ->
int Signal(string sym, int period)
This is how the flow is now.
int OnInit()
{
EventSetTimer(5);
return(INIT_SUCCEEDED);
}
....
void OnTimer()
{
LoopThruSym(symbols);
}
....
void LoopThruSym(string listOfSym)
{
if(Mode == All)
{
int i;
int numSymbolmarketWatch=SymbolsTotal(false);
numSymbols=numSymbolmarketWatch;
ArrayResize(symbolListFinal,numSymbolmarketWatch);
for(i=0; i<numSymbolmarketWatch; i++)
{
symbolListFinal[i]=SymbolName(i,false);
}
}
else
if(Mode == Selected)
{
string sep=",";
ushort u_sep;
int i;
u_sep=StringGetCharacter(sep,0);
StringSplit(listOfSym,u_sep,symbolList);
numSymbols=ArraySize(symbolList);
ArrayResize(symbolListFinal,numSymbols);
for(i=0; i<numSymbols; i++)
{
symbolListFinal[i]=symbolPrefix+symbolList[i]+symbolSuffix;
LoopThruPeriod(symbolListFinal[i],periods, numSymbols);
}
}
else
if(Mode == Current)
{
LoopThruPeriod(Symbol(),periods,numSymbols);
}
return;
}
....
void LoopThruPeriod(string sym, string listOfPeriods, int listOfSym)
{
if(ModePeriod == All_Period)
{
string periodsALL = "1,5,15,30,60,240,1440,10080,43200";
string sep=",";
ushort u_sep;
int i;
int lastTradeBarArrayCount;
u_sep=StringGetCharacter(sep,0);
StringSplit(periodsALL,u_sep,periodList);
numPeriods=ArraySize(periodList);
ArrayResize(periodListFinal,numPeriods);
lastTradeBarArrayCount = listOfSym+numPeriods;
ArrayResize(lastTradeBarArray,lastTradeBarArrayCount);
for(i=0; i<numPeriods; i++)
{
periodListFinal[i]=symbolPrefix+periodList[i]+symbolSuffix;
Trade(sym,StrToInteger(periodListFinal[i]));
Comment("lastTradeBarArrayCount = "+lastTradeBarArrayCount);
}
}
else
if(ModePeriod == Selected_Period)
{
string sep=",";
ushort u_sep;
int i;
int lastTradeBarArrayCount;
u_sep=StringGetCharacter(sep,0);
StringSplit(listOfPeriods,u_sep,periodList);
numPeriods=ArraySize(periodList);
ArrayResize(periodListFinal,numPeriods);
lastTradeBarArrayCount = listOfSym*numPeriods;
ArrayResize(lastTradeBarArray,lastTradeBarArrayCount);
for(i=0; i<numPeriods; i++)
{
periodListFinal[i]=symbolPrefix+periodList[i]+symbolSuffix;
Trade(sym,StrToInteger(periodListFinal[i]));
Comment("lastTradeBarArrayCount = "+lastTradeBarArrayCount);
}
}
if(ModePeriod == Current_Period)
{
Trade(sym,Period());
}
}
...
void Trade(string sym, int period)
{
//Print("Symbole = " + sym + " : " + period);
if(OrderMethod == BuyandSell)
{
if(Signal(sym,period) == 1 && CheckMoneyForTrade(sym,Lots,OP_BUY) && CheckVolumeValue(sym,Lots))
LimitBuy(sym,period);
else
if(Signal(sym,period) == -1 && CheckMoneyForTrade(sym,Lots,OP_SELL) && CheckVolumeValue(sym,Lots))
LimitSell(sym,period);
}
else
if(OrderMethod == BuyOnly)
{
if(Signal(sym,period) == 1 && CheckMoneyForTrade(sym,Lots,OP_BUY) && CheckVolumeValue(sym,Lots))
LimitBuy(sym,period);
}
else
if(OrderMethod == SellOnly)
{
if(Signal(sym,period) == -1 && CheckMoneyForTrade(sym,Lots,OP_SELL) && CheckVolumeValue(sym,Lots))
LimitSell(sym,period);
}
//Trail(sym);
return;
}
...
int Signal(string sym, int period)
{
if(lastTradeBar!=Time[0])
{
if(PFTP_BuySignal > 0 && PFTP_BuySignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_BuySL;
return (1);
}
if(PFTP_SellSignal > 0 && PFTP_SellSignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_SellSL;
return (-1);
}
else
return (0);
lastTradeBar=Time[0];
};
return (0);
}
Code a function on the "void OnTick()" like this:
void OnTick()
{
//---
CheckForSignal();
}
And then code the function "CheckForSignal()"
//+------------------------------------------------------------------+
//| Function "CheckForSignal()" |
//+------------------------------------------------------------------+
void CheckForSignal(){
//check here a bar until a Signal given Signal given then initialize it to Time[]
static datetime candletime=0;
if(candletime!=Time[0]){
double upArrow=iCustom(your Custom indicator or whatever parameters);
if(upArrow != EMPTY_VALUE){
EnterTrade(OP_BUY);
}
double downArrow=iCustom(your Custom indicator or whatever parameters);
if(downArrow != EMPTY_VALUE){
EnterTrade(OP_SELL);
}
// if we have a Signal we will initialize candle time to Time[0] to avoid multiple Orders
candletime=Time[0];
}
}
//+------------------------------------------------------------------+
Then Send Signal to Open or Close or whatever you need in my example we will open Trades
//+------------------------------------------------------------------+
//| Function "EnterTrade()" |
//+------------------------------------------------------------------+
void EnterTrade(int type){
int err=0;
double price=0;
double sl=0;
double tp=0;
if(type == OP_BUY){
price=Ask;
}else{
price=Bid;
}
//steppoin8-step15: replace function "OrderSend" parameter
// ->variablename "name" (magic)
//steppoint8-step16: end ";"
int ticket=OrderSend(Symbol(),type,LotSize,price,slippage,0,0,"EA Trade",magic,0,clrMagenta);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET)){
if(OrderType()==OP_BUY){
sl=OrderOpenPrice()-(stopLoss*pips);
tp=OrderOpenPrice()+(takeProfit*pips);
}else if(OrderType()==OP_SELL){
sl= OrderOpenPrice()+(stopLoss*pips);
tp= OrderOpenPrice()-(takeProfit*pips);
}
if(!OrderModify(ticket,price,sl,tp,0,clrMagenta)){
err=GetLastError();
Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err));
}
}else{
Print("Failed to Select Order",ticket);
err=GetLastError();
Print("Encountered an error while selecting order"+(string)ticket+" error number"+(string)err+" "+ErrorDescription(err));
}
}
else{
err=GetLastError();
Print("Encountered an error during order placement"+(string)err+" "+ErrorDescription(err));
}
}
//+------------------------------------------------------------------+
This is not an answer more of like progress.
So what i'm doing not instead of checking for candletime=Time[0] I check then the last trade close time is for that sym/magic nr and comment. and then runing it thru if(iBarShift(sym,period,OrderCloseTime()) > 1)
this kinda works but I'm getting problems down the road if I'm trying to use symbols with different miniLots. But that will come on another post.
bool getLastOrderClose(string sym, int period)
{
if(OrdersHistoryTotal() == 0)
return true;
string comment = "Multi Currency "+sym+":"+IntegerToString(period);
int count = 0;
int tradesPerSymbole =0;
for(int i=OrdersHistoryTotal()-1; i >= 0; i--)
if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
{
if(OrderSymbol() == sym)
{
if(OrderMagicNumber() == Magic)
{
tradesPerSymbole++;
if(StringFind(comment,OrderComment())<0)
{
if(iBarShift(sym,period,OrderCloseTime()) > 1)
{
return true;
}
}
}
}
}
else
{
Print(sym +" : "+"OrderSend() - getLastOrderClose - error - ", ErrorDescription(GetLastError()));
}
if(tradesPerSymbole == 0)
return true;
return false;
};
//OrderSend('EURUSD',blablabla Parameter)
//OrderSend('GBPUSD',blablabla Parameter)
//OrderSend('USDJPY',blablabla Parameter)
//OrderSend('EURCHF',blablabla Parameter)
int ticket=OrderSend('EURUSD',type,LotSize,price,slippage,0,0,"EA Trade",magic,0,clrMagenta);
for(int I=ticket;ticket<Orderstotal();i++){
if(OrderSelect(ticket,SELECT_BY_TICKET)){
if(OrderType()==OP_BUY){
sl=OrderOpenPrice()-(stopLoss*pips);
tp=OrderOpenPrice()+(takeProfit*pips);
}else if(OrderType()==OP_SELL){
sl= OrderOpenPrice()+(stopLoss*pips);
tp= OrderOpenPrice()-(takeProfit*pips);
}
if(!OrderModify(ticket,price,sl,tp,0,clrMagenta)){
err=GetLastError();
Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err));
}
}else{
Print("Failed to Select Order",ticket);
err=GetLastError();
Print("Encountered an error while selecting order"+(string)ticket+" error number"+(string)err+" "+ErrorDescription(err));
}
}
else{
err=GetLastError();
Print("Encountered an error during order placement"+(string)err+" "+ErrorDescription(err));
}
}
//+------------------------------------------------------------------+
I think its not the pro solution but I would declare a Ordersend function for all the pairs where u want to open the order (I need not to say that the order send function should be declared in a conditional so only the the real ordersend be placed)
but the part where I want your attention is you can do it the hardware by declaring the Ordersend(not with Symbol() instead of that with "YourPairname");
hope this help you a little bit to reach your goal gl
i am new with Opencv.I use JavaCameraView,
which uses 1280x 720 camera resolution.
How can I increase the resolution to 5 megapixels?
Please help me :)
You need to pick a resolution that is allowed by your camera. Call the following code in your onCameraViewStarted function and set listNum so that it corresponds to the resolution you desire:
Parameters params = mCamera.getParameters();
List<Size> resList = mCamera.getParameters().getSupportedPictureSizes();
int listNum = 1;// 0 is the maximum resolution
int width = resList.get(listNum).width;
int height = resList.get(listNum).height;
params.setPictureSize(width, height);
mCamera.setParameters(params);
mCamera is your org.opencv.android.JavaCameraView object.
Brian
It seems that OpenCV Camera (JavaCameraView) has been set to default maximum resolution of 1280*720.
We can decrease the resolution using:
cameraView.setMaxFrameSize(320, 280);
Or
cameraView.setMaxFrameSize(480, 320);
Or
cameraView.setMaxFrameSize(640, 480);
Or
cameraView.setMaxFrameSize(800, 600);
Or
cameraView.setMaxFrameSize(1280, 720);
Now, the question is how to increase the resolution after that, if my mobile supports more resolution. For that we have to make our own customized JavaCameraView (Let's say MyCameraView).
Just copy and paste JavaCameraView to MyCameraView and do corrections according to your need.
I do the following corrections in my case:
package com.example.opencvcamera;
import org.opencv.android.CameraBridgeViewBase;
import android.hardware.Camera;
import java.util.List;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
/**
* Created by Kumar.Vaibhav on 19-04-2017.
*/
public class MyCameraView extends CameraBridgeViewBase implements Camera.PreviewCallback {
private static final int MAGIC_TEXTURE_ID = 10;
private static final String TAG = "MyCameraView";
private byte mBuffer[];
private Mat[] mFrameChain;
private int mChainIdx = 0;
private Thread mThread;
private boolean mStopThread;
protected Camera mCamera;
protected MyCameraView.JavaCameraFrame[] mCameraFrame;
private SurfaceTexture mSurfaceTexture;
public static class JavaCameraSizeAccessor implements ListItemAccessor {
#Override
public int getWidth(Object obj) {
Camera.Size size = (Camera.Size) obj;
return size.width;
}
#Override
public int getHeight(Object obj) {
Camera.Size size = (Camera.Size) obj;
return size.height;
}
}
public MyCameraView(Context context, int cameraId) {
super(context, cameraId);
}
public MyCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected boolean initializeCamera(int width, int height) {
Log.d(TAG, "Initialize java camera");
boolean result = true;
synchronized (this) {
mCamera = null;
if (mCameraIndex == CAMERA_ID_ANY) {
Log.d(TAG, "Trying to open camera with old open()");
try {
mCamera = Camera.open();
}
catch (Exception e){
Log.e(TAG, "Camera is not available (in use or does not exist): " + e.getLocalizedMessage());
}
if(mCamera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
boolean connected = false;
for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")");
try {
mCamera = Camera.open(camIdx);
connected = true;
} catch (RuntimeException e) {
Log.e(TAG, "Camera #" + camIdx + "failed to open: " + e.getLocalizedMessage());
}
if (connected) break;
}
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
int localCameraIndex = mCameraIndex;
if (mCameraIndex == CAMERA_ID_BACK) {
Log.i(TAG, "Trying to open back camera");
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
Camera.getCameraInfo( camIdx, cameraInfo );
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
localCameraIndex = camIdx;
break;
}
}
} else if (mCameraIndex == CAMERA_ID_FRONT) {
Log.i(TAG, "Trying to open front camera");
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
Camera.getCameraInfo( camIdx, cameraInfo );
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
localCameraIndex = camIdx;
break;
}
}
}
if (localCameraIndex == CAMERA_ID_BACK) {
Log.e(TAG, "Back camera not found!");
} else if (localCameraIndex == CAMERA_ID_FRONT) {
Log.e(TAG, "Front camera not found!");
} else {
Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(localCameraIndex) + ")");
try {
mCamera = Camera.open(localCameraIndex);
} catch (RuntimeException e) {
Log.e(TAG, "Camera #" + localCameraIndex + "failed to open: " + e.getLocalizedMessage());
}
}
}
}
if (mCamera == null)
return false;
/* Now set camera parameters */
try {
Camera.Parameters params = mCamera.getParameters();
Log.d(TAG, "getSupportedPreviewSizes()");
List<android.hardware.Camera.Size> sizes = params.getSupportedPreviewSizes();
if (sizes != null) {
/* Select the size that fits surface considering maximum size allowed */
//Size frameSize = calculateCameraFrameSize(sizes, new MyCameraView.JavaCameraSizeAccessor(), width, height);
Camera.Size mSizePicture =sizes.get(0);
if(mSizePicture.width<3264 && mSizePicture.height<2448)
{
int cameraSize= sizes.size();
mSizePicture =sizes.get(cameraSize-1);
}
/*params.setPreviewFormat(ImageFormat.NV21);
Log.d(TAG, "Set preview size to " + Integer.valueOf((int)frameSize.width) + "x" + Integer.valueOf((int)frameSize.height));
params.setPreviewSize((int)frameSize.width, (int)frameSize.height);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && !android.os.Build.MODEL.equals("GT-I9100"))
params.setRecordingHint(true);*/
List<String> FocusModes = params.getSupportedFocusModes();
if (FocusModes != null && FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
{
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mCamera.setParameters(params);
params = mCamera.getParameters();
mFrameWidth = params.getPreviewSize().width;
mFrameHeight = params.getPreviewSize().height;
if ((getLayoutParams().width == LayoutParams.MATCH_PARENT) && (getLayoutParams().height == LayoutParams.MATCH_PARENT))
mScale = Math.min(((float)height)/mFrameHeight, ((float)width)/mFrameWidth);
else
mScale = 0;
if (mFpsMeter != null) {
mFpsMeter.setResolution(mFrameWidth, mFrameHeight);
}
int size = mFrameWidth * mFrameHeight;
size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
mBuffer = new byte[size];
mCamera.addCallbackBuffer(mBuffer);
mCamera.setPreviewCallbackWithBuffer(this);
mFrameChain = new Mat[2];
mFrameChain[0] = new Mat(mFrameHeight + (mFrameHeight/2), mFrameWidth, CvType.CV_8UC1);
mFrameChain[1] = new Mat(mFrameHeight + (mFrameHeight/2), mFrameWidth, CvType.CV_8UC1);
AllocateCache();
mCameraFrame = new MyCameraView.JavaCameraFrame[2];
mCameraFrame[0] = new MyCameraView.JavaCameraFrame(mFrameChain[0], mFrameWidth, mFrameHeight);
mCameraFrame[1] = new MyCameraView.JavaCameraFrame(mFrameChain[1], mFrameWidth, mFrameHeight);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mSurfaceTexture = new SurfaceTexture(MAGIC_TEXTURE_ID);
mCamera.setPreviewTexture(mSurfaceTexture);
} else
mCamera.setPreviewDisplay(null);
/* Finally we are ready to start the preview */
Log.d(TAG, "startPreview");
mCamera.startPreview();
}
else
result = false;
} catch (Exception e) {
result = false;
e.printStackTrace();
}
}
return result;
}
protected void releaseCamera() {
synchronized (this) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
}
mCamera = null;
if (mFrameChain != null) {
mFrameChain[0].release();
mFrameChain[1].release();
}
if (mCameraFrame != null) {
mCameraFrame[0].release();
mCameraFrame[1].release();
}
}
}
private boolean mCameraFrameReady = false;
#Override
protected boolean connectCamera(int width, int height) {
/* 1. We need to instantiate camera
* 2. We need to start thread which will be getting frames
*/
/* First step - initialize camera connection */
Log.d(TAG, "Connecting to camera");
if (!initializeCamera(width, height))
return false;
mCameraFrameReady = false;
/* now we can start update thread */
Log.d(TAG, "Starting processing thread");
mStopThread = false;
mThread = new Thread(new CameraWorker());
mThread.start();
return true;
}
#Override
protected void disconnectCamera() {
/* 1. We need to stop thread which updating the frames
* 2. Stop camera and release it
*/
Log.d(TAG, "Disconnecting from camera");
try {
mStopThread = true;
Log.d(TAG, "Notify thread");
synchronized (this) {
this.notify();
}
Log.d(TAG, "Wating for thread");
if (mThread != null)
mThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mThread = null;
}
/* Now release camera */
releaseCamera();
mCameraFrameReady = false;
}
#Override
public void onPreviewFrame(byte[] frame, Camera arg1) {
Log.d(TAG, "Preview Frame received. Frame size: " + frame.length);
synchronized (this) {
mFrameChain[mChainIdx].put(0, 0, frame);
mCameraFrameReady = true;
this.notify();
}
if (mCamera != null)
mCamera.addCallbackBuffer(mBuffer);
}
private class JavaCameraFrame implements CvCameraViewFrame {
#Override
public Mat gray() {
return mYuvFrameData.submat(0, mHeight, 0, mWidth);
}
#Override
public Mat rgba() {
Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
return mRgba;
}
public JavaCameraFrame(Mat Yuv420sp, int width, int height) {
super();
mWidth = width;
mHeight = height;
mYuvFrameData = Yuv420sp;
mRgba = new Mat();
}
public void release() {
mRgba.release();
}
private Mat mYuvFrameData;
private Mat mRgba;
private int mWidth;
private int mHeight;
};
private class CameraWorker implements Runnable {
#Override
public void run() {
do {
boolean hasFrame = false;
synchronized (MyCameraView.this) {
try {
while (!mCameraFrameReady && !mStopThread) {
MyCameraView.this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (mCameraFrameReady)
{
mChainIdx = 1 - mChainIdx;
mCameraFrameReady = false;
hasFrame = true;
}
}
if (!mStopThread && hasFrame) {
if (!mFrameChain[1 - mChainIdx].empty())
deliverAndDrawFrame(mCameraFrame[1 - mChainIdx]);
}
} while (!mStopThread);
Log.d(TAG, "Finish processing thread");
}
}
}
Also change the activity_main.xml to as follows:
<com.example.opencvcamera.MyCameraView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/java_camera_view"
android:visibility="visible"/>
I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate
I have a 3 GSM phones and a 3 verizon (CDMA) phones. I have a BB application in which the location listener is set to a 5 minute interval.
For 2 of the verizon phones the application's location update method gets called frequently. For the rest, the location listener gets called at a regular 5 minute interval.
What could be causing this difference in behavior?
public synchronized void locationUpdated(LocationProvider locationProvider, Location location) {
if (enabled) {
if (blackberryProvider != null) {
try {
constructCriteria(GPSInfo.GPS_MODE_CELLSITE);
gpsUpdate();
} catch (LocationException e) {
log stuff//
}
}
}
}
private void gpsUpdate() throws LocationException, InterruptedException {
try {
String gpsMode = null;
if (bbCriteria.getMode() == GPSInfo.GPS_MODE_CELLSITE) {
gpsMode = "cellsiteMode";
}
if (gpsMode == "cellsiteMode" && gpsMode.length() > 0 && bbProvider != null) {
// variable declaration
try {
bbLocation = (BlackBerryLocation) bbProvider.getLocation(10);
} catch (LocationException e) {
bbLocation = null;
}
if (bbLocation != null) {
// do stuff
// store location in the database
}
}
}
}
}
}
private void constructCriteria(final int mode) {
blackberryCriteria = null;
blackberryProvider = null;
blackberryCriteria = new BlackBerryCriteria();
blackberryCriteria.setSatelliteInfoRequired(true, false);
if (mode == GPSInfo.GPS_MODE_CELLSITE) {
setCriteraForCellSite();
}
try {
blackberryProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(blackberryCriteria);
if (iLocationListner == null) {
iLocationListner = new ILocationListner();
blackberryProvider.setLocationListener(iLocationListner, locationInterval == 0 ? 300 : locationInterval, -1, -1);
} else {
blackberryProvider.setLocationListener(iLocationListner, locationInterval == 0 ? 300 : locationInterval, -1, -1);
}
} catch (LocationException lex) {
Logger.log("LocationEventSource constructor", lex);
return;
}
}
You are setting your criteria to update every 300 seconds if locationInterval == 0 or at the default rate (once per second) otherwise. Is this really what you want? Where is locationInterval initialized? How does its value change as the program runs?
I am building an AppWorld sort of thing in blackberry.I have Categories,sub categories and apps within.I want to do in-app download,but as of now i am calling the browser and passing the url and downloading of the content happens.How to make in-app download or download from within my app just like the AppWorld of blackberry.
YOu need to use code module manager API to download and install applications.
Code in bits and pieces
_moduleGroup = new CodeModuleGroup(appVendorName);
_moduleGroup.setVersion(JADParser.getValue("MIDlet-Version"));
_moduleGroup.setVendor(vendorName);
_moduleGroup.setFriendlyName(appName);
_moduleGroup.setDescription(JADParser.getValue("MIDlet-Description"));
String dependency = JADParser.getValue("RIM-COD-Module-Dependencies");
if (dependency != null)
{
dependency = dependency.trim();
String[] dependencyList = vStringUtils.split(dependency, ',');
for (int i = 0; i < dependencyList.length; i++)
{
_moduleGroup.addDependency(dependencyList[i]);
}
}
for (i = 0; i < count; i++)
{
if (!writeCODFile(getCodFileData(i), getCodFileName(i)))
{
throw new Exception();
}
}
private boolean writeCODFile(byte[] data, String fileName)
{
boolean isSuccess = true;
int moduleId = 0;
if (data.length > MODULE_SIZE_LIMIT)
{
moduleId = CodeModuleManager.createNewModule(data.length, data, MODULE_SIZE_LIMIT);
isSuccess = CodeModuleManager.writeNewModule(moduleId, MODULE_SIZE_LIMIT, data, MODULE_SIZE_LIMIT, data.length - MODULE_SIZE_LIMIT);
}
else
{
moduleId = CodeModuleManager.createNewModule(data.length, data, data.length);
}
if (moduleId > 0 && isSuccess)
{
int ret = CodeModuleManager.saveNewModule(moduleId, true, _transactionId);
if (ret == CodeModuleManager.CMM_OK_MODULE_OVERWRITTEN || ret == CodeModuleManager.CMM_OK)
{
return true;
}
}
return false;
}