GUI not updating update after purchasing inApp Billing android - in-app-purchase

Ok so here my GUI is suppossed to update when the purchases are complete. I am using android.test.purchase and the GUI is not updating should i be worried or no?
Variables
IabHelper mHelper;
static final String TAG = "com.back.to.school.zone.readingLevelPicker";
// SKUs for our products: the premium upgrade (non-consumable)
static final String SKU_PREMIUM = "android.test.refunded";
// Does the user have the premium upgrade?
boolean mIsPremium = false;
// (arbitrary) request code for the purchase flow
static final int RC_REQUEST = 20;
onCreate method
String base64EncodedPublicKey = "<my key is in here>";
mHelper = new IabHelper(this, base64EncodedPublicKey);
//It is recommended to add more security than just pasting it in your source code;
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
a Button to buy the needed items
buyButton = (Button) findViewById(R.id.buyButtonS);
buyButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mHelper.launchPurchaseFlow(readingLevelPicker.this, SKU_PREMIUM, 10001,
mPurchaseFinishedListener, "");
}
One of the buttons that need to be enabled and the end of the on create method after mLevel10
mLevel10.setEnabled(false);
mLevel10.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(),
readingMode10.class); // Coming soon
startActivityForResult(myIntent, 0);
}
});
} //end of oncreate method
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
else {
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
// update UI accordingly
mLevel6 = (Button) findViewById(R.id.level6);
mLevel7 = (Button) findViewById(R.id.level7);
mLevel8 = (Button) findViewById(R.id.level8);
mLevel9 = (Button) findViewById(R.id.level9);
mLevel10 = (Button) findViewById(R.id.level10);
mLevel6.setEnabled(true);
mLevel7.setEnabled(true);
mLevel8.setEnabled(true);
mLevel9.setEnabled(true);
mLevel10.setEnabled(true);
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_PREMIUM)) {
// give user access to premium content and update the UI
mLevel6 = (Button) findViewById(R.id.level6);
mLevel7 = (Button) findViewById(R.id.level7);
mLevel8 = (Button) findViewById(R.id.level8);
mLevel9 = (Button) findViewById(R.id.level9);
mLevel10 = (Button) findViewById(R.id.level10);
mLevel6.setEnabled(true);
mLevel7.setEnabled(true);
mLevel8.setEnabled(true);
mLevel9.setEnabled(true);
mLevel10.setEnabled(true);
}
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + ","
+ data);
// Pass on the activity result to the helper for handling
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
} else {
Log.d(TAG, "onActivityResult handled by IABUtil.");
}
}
some comments - from my understand everything is working as far as the billing methods goes because when using android.test.purchased it says payment completed. BUT THE UI does not enable the text boxes, therefore leaving the textboxes disabled, ive tried to throw a break point at the location mLevel7.setEnabled("true") but it doesnt show anything out of the ordinary no failures are presented the UI just is not updating? why?

make sure you are not testing for the queryInvetory method, because it will work only when you are trying to purchase real product instead of dummy product(android.test.purchased), because google will not keep record for the dummy product according to my knowledge.
onCreate() method
Define all variables in the oncreate method and just change textbox
enable-disable in the queryInventory and IabPurchaseFinishListener.
mLevel6 = (Button) findViewById(R.id.level6);
mLevel7 = (Button) findViewById(R.id.level7);
mLevel8 = (Button) findViewById(R.id.level8);
mLevel9 = (Button) findViewById(R.id.level9);
mLevel10 = (Button) findViewById(R.id.level10);
QueryInventoryFinishedListener
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
//else { // you don't need to check for the failure then go if and other wise else.
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
// update UI accordingly
if(mIsPremium){
mLevel6.setEnabled(true);
mLevel7.setEnabled(true);
mLevel8.setEnabled(true);
mLevel9.setEnabled(true);
mLevel10.setEnabled(true);
}
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
// }
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
OnIabPurchaseFinishedListener
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
if (purchase.getSku().equals(SKU_PREMIUM)) { // same as above you don't need to check else if condition again
// give user access to premium content and update the UI
mLevel6.setEnabled(true);
mLevel7.setEnabled(true);
mLevel8.setEnabled(true);
mLevel9.setEnabled(true);
mLevel10.setEnabled(true);
}
}
};
Let me know it is working for you or not.

Related

How to update pin information on google map using xamarin

It is necessary to replace the direct connection to the database with API.
I use this code to directly connect to MySQL db and change pin information:
public async void DatabaseConnection(List<CustomPin> pins)
{
string ConnectionString = "server=192.168.0.1;uid=user;port=4444;pwd=pass;database=dbName;";
MySqlConnection Conn = new MySqlConnection(ConnectionString);
try
{
Conn.Open();
string query = "SELECT * FROM sel_alert_level s;";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
int codeNum = myReader.GetInt32(4);
int level = myReader.GetInt32(3);
int mapCode = myReader.GetInt32(0);
foreach (var item in pins)
{
if (item.CodeNum == codeNum)
{
item.AlertLevel = level;
item.CodeNum = codeNum;
item.MapCode = mapCode;
//await DisplayAlert("Alert", mapCode.ToString(), "ok");
}
}
//await DisplayAlert("Database Connection", "Connected .." + Environment.NewLine + myReader.GetInt32(0) + Environment.NewLine + myReader.GetString(1) + Environment.NewLine + myReader.GetString(2) + Environment.NewLine + myReader.GetInt32(3) + Environment.NewLine + myReader.GetInt32(4), "OK");
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
catch (Exception ex)
{
await DisplayAlert("Database Connection", "Not Connected ..." + Environment.NewLine + ex.ToString(), "OK");
}
}
With this code I successfully update the pin information.
Now I create the same method with API Response and what to do the same like DatabaseConnection(); just try to update the information, but not work for me :(
public async void APIConnection(List<CustomPin> pins)
{
try
{
WaterBindingData waterData = await _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var water in waterData.WaterStation.Stations)
{
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = water.AlertLevelStation;
item.CodeNum = water.CodeNum;
item.MapCode = water.MapCode;
}
}
}
}
catch (Exception ex)
{
await DisplayAlert("Data Alert", "Error:" + Environment.NewLine + ex.ToString(), "OK");
}
}
I not have any errors here. waterData come with the data, but data not changed in the pins.. I don't know why...
And Now my information are not changed ..
MapCode and other variables not changed.
I call this two methods in the constructor like that:
DatabaseConnection(customMap.CustomPins);
APIConnection(customMap.CustomPins);
So... When I start the project I receive message like this:
/Applications/Visual Studio.app/Contents/Resources/lib/monodevelop/bin/MSBuild/Current/bin/Microsoft.Common.CurrentVersion.targets(5,5): Warning MSB3276: Found conflicts between different versions of the same dependent assembly. Please set the "AutoGenerateBindingRedirects" property to true in the project file. For more information, see http://go.microsoft.com/fwlink/?LinkId=294190. (MSB3276) (MaritsaTundzhaForecast.iOS)
And I check this link but I not have properties option, because I use mac. I have only options on the projects.
Is it possible that this does not change the content in the pins аnd what would be the reason it didn't work ?
I checked the if statement in the loop and she work:
Since it is an asynchronous method , I suggest you try to assign customMap.CustomPins in APIConnection method .
Something like that
//constructor
List<CustomPin> pins = xxxxx;
APIConnection(pins);
public async void APIConnection(List<CustomPin> pins)
{
try
{
WaterBindingData waterData = await _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var water in waterData.WaterStation.Stations)
{
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = water.AlertLevelStation;
item.CodeNum = water.CodeNum;
item.MapCode = water.MapCode;
}
}
}
customMap.CustomPins = pins; //assign the value in this line
}
catch (Exception ex)
{
await DisplayAlert("Data Alert", "Error:" + Environment.NewLine + ex.ToString(), "OK");
}
}

Xamarin-IOS BTLE WroteCharacteristicValue not fired

I have the following code for my IOS implementation, the problem is that the WroteCharacteristicValue event is never fired. Is is being fired on the android side when I connect to the same module. Any ideas what to do?
public void StartUpdates ()
{
// TODO: should be bool RequestValue? compare iOS API for commonality
bool successful = false;
if(CanRead) {
Console.WriteLine ("** Characteristic.RequestValue, PropertyType = Read, requesting read");
_parentDevice.UpdatedCharacterteristicValue += UpdatedRead;
_parentDevice.ReadValue (_nativeCharacteristic);
successful = true;
}
if (CanUpdate) {
Console.WriteLine ("** Characteristic.RequestValue, PropertyType = Notify, requesting updates");
_parentDevice.UpdatedCharacterteristicValue += UpdatedNotify;
_parentDevice.WroteCharacteristicValue += Wrote; // -DP here??
_parentDevice.SetNotifyValue (true, _nativeCharacteristic);
successful = true;
}
Console.WriteLine ("** RequestValue, Succesful: " + successful.ToString());
}
void Wrote(object sender, CBCharacteristicEventArgs e) {
System.Diagnostics.Debug.WriteLine("Characteristic Write Complete!");
this.WriteComplete (this, new CharacteristicReadEventArgs () {
Characteristic = new Characteristic(e.Characteristic, _parentDevice)
});
}
The WroteCharacteristic will only fire if the characteristic writes with response.
You can check it with:
var prop = _nativeCharacteristic.Properties;
if(prop.HasFlag(CBCharacteristicProperties.Write))
{
// Event can be used
}
else if(prop.HasFlag(CBCharacteristicProperties.WriteWithoutResponse))
{
// Event will not fire if WriteWithoutResponse
}
Btw: we provide a plugin for BLE, so you don't have to care about platform sepcific stuff ;) http://smstuebe.de/2016/05/13/blev1.0/

How to stop progressbar in blackberry

In BlackBerry, my application is working perfectly fine. But one Requirement is when I load data from server, a progress bar is showing. If it takes so much time to load data from server, then I want to stop the progress bar. In BlackBerry, on back key pressed, it is not working. Please help me.
public class WaitScreen extends PopupScreen
{
public WaitScreen(String msg) {
super(new HorizontalFieldManager());
add(new LabelField(msg));
AnimatedGIFField testanimated = new AnimatedGIFField(
(GIFEncodedImage) (GIFEncodedImage.getEncodedImageResource("ajax_loader.gif")),
AnimatedGIFField.FIELD_HCENTER | AnimatedGIFField.FIELD_VCENTER);
add(testanimated);
}
}
public long timeout=0;
t.schedule(new TimerTask() {
public void run()
{
// TODO Auto-generated method stub
timeout+=1;
System.out.println("Timeout value:"+timeout);
if(timeout>=28)
{
//timeout every 1 munite
System.out.println("Timeout value:"+timeout);
System.out.println("closing connection");
try
{
parent.notifyDestroyed();
}
catch (Exception ex)
{
System.out.println("Exception is:"+ex);
}
this.cancel();
}
}
}, 0, 1000);
// Thread.sleep(30000);
httpconn_post = (HttpConnection) Connector.open(url);
httpconn_post.setRequestMethod(HttpConnection.POST);
httpconn_post.setRequestProperty("Accept_Language","en-US");
httpconn_post.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = httpconn_post.openOutputStream();
out.write(param.getBytes());
out.flush();
System.out.println("Status Line Code: " + httpconn_post.getResponseCode());
System.out.println("Status Line Message: " + httpconn_post.getResponseMessage());
if ( httpconn_post.getResponseCode()== HttpConnection.HTTP_OK )
{
is=httpconn_post.openDataInputStream();
// cancelling timer
t.cancel();
.....
.....
}
I had done this using this code..I had done it successfully..

Issue in Invoking camera and saving images in SD card

In my task I have to invoke camera in a button click and take picture and have to save it and display the image in the same screen. I have tried it and succeed in emulator. but its not working in real device. getting some errors. tried a lot. but cant able to find out the issue. more over, Its working perfectly in 9700 emulator and showing some error in 9500.
public class CameraScreen extends MainScreen implements FieldChangeListener
{
/** The camera's video controller */
private VideoControl _videoControl;
private Field _videoField;
private EncodingProperties[] _encodings;
private int _indexOfEncoding = 0;
private static String FILE_NAME = System.getProperty("fileconn.dir.photos")+"IMAGE"; //"file:///SDCard/" + "myphotos/" + "IMAGE";//
private static String EXTENSION = ".bmp";
private static int _counter;
int flag = 0;
BitmapField imageField = new BitmapField();
HorizontalFieldManager menuBar = new HorizontalFieldManager(Field.USE_ALL_WIDTH);
VerticalFieldManager main_vfm = new VerticalFieldManager();
VerticalFieldManager camera_vfm = new VerticalFieldManager();
VerticalFieldManager image_vfm = new VerticalFieldManager();
ButtonField bt = new ButtonField("Click",ButtonField.CONSUME_CLICK);
ButtonField front_bt = new ButtonField("Front",ButtonField.CONSUME_CLICK);
ButtonField back_bt = new ButtonField("Back",ButtonField.CONSUME_CLICK);
ButtonField side1_bt = new ButtonField("Side 1",ButtonField.CONSUME_CLICK);
ButtonField side2_bt = new ButtonField("Side 2",ButtonField.CONSUME_CLICK);
public CameraScreen()
{
setTitle("First Screen");
bt.setChangeListener(this);
front_bt.setChangeListener(this);
back_bt.setChangeListener(this);
side1_bt.setChangeListener(this);
side2_bt.setChangeListener(this);
image_vfm.add(menuBar);
menuBar.add(front_bt);
menuBar.add(back_bt);
menuBar.add(side1_bt);
menuBar.add(side2_bt);
image_vfm.add(bt);
try {
Bitmap image = Bitmap.createBitmapFromBytes( readFile(),0, -1, 5 );
imageField.setBitmap(image);
image_vfm.add(imageField);
} catch(Exception e) {
System.out.println(e.toString());
}
main_vfm.add(image_vfm);
add(main_vfm);
front_bt.setFocus();
// Initialize the camera object and video field
initializeCamera();
// Initialize the list of possible encodings
initializeEncodingList();
// If the field was constructed successfully, create the UI
if(_videoField != null)
{
createUI();
}
// If not, display an error message to the user
else
{
camera_vfm.add( new RichTextField( "Error connecting to camera." ) );
}
}
/**
* Takes a picture with the selected encoding settings
*/
public void takePicture()
{
try
{
// A null encoding indicates that the camera should
// use the default snapshot encoding.
String encoding = null;
if( _encodings != null )
{
// Use the user-selected encoding
encoding = _encodings[_indexOfEncoding].getFullEncoding();
}
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
createImageScreen( _videoControl.getSnapshot( encoding ) );
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
}
}
/**
* Prevent the save dialog from being displayed
* #see net.rim.device.api.ui.container.MainScreen#onSavePrompt()
*/
protected boolean onSavePrompt()
{
return true;
}
/**
* Initializes the Player, VideoControl and VideoField
*/
private void initializeCamera()
{
try
{
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer( "capture://video" );
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
// Grab the video control and set it to the current display
_videoControl = (VideoControl)player.getControl( "VideoControl" );
if (_videoControl != null)
{
// Create the video field as a GUI primitive (as opposed to a
// direct video, which can only be used on platforms with
// LCDUI support.)
_videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
//_videoControl.setDisplaySize(50, 50);
_videoControl.setVisible(true);
}
// Set the player to the STARTED state (see Player javadoc)
player.start();
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
}
}
/**
* Initialize the list of encodings
*/
private void initializeEncodingList()
{
try
{
// Retrieve the list of valid encodings
String encodingString = System.getProperty("video.snapshot.encodings");
// Extract the properties as an array of word
String[] properties = StringUtilities.stringToKeywords(encodingString);
// The list of encodings
Vector encodingList = new Vector();
//Strings representing the four properties of an encoding as
//returned by System.getProperty().
String encoding = "encoding";
String width = "width";
String height = "height";
String quality = "quality";
EncodingProperties temp = null;
for(int i = 0; i < properties.length ; ++i)
{
if( properties[i].equals(encoding))
{
if(temp != null && temp.isComplete())
{
// Add a new encoding to the list if it has been
// properly set.
encodingList.addElement( temp );
}
temp = new EncodingProperties();
// Set the new encoding's format
++i;
temp.setFormat(properties[i]);
}
else if( properties[i].equals(width))
{
// Set the new encoding's width
++i;
temp.setWidth(properties[i]);
}
else if( properties[i].equals(height))
{
// Set the new encoding's height
++i;
temp.setHeight(properties[i]);
}
else if( properties[i].equals(quality))
{
// Set the new encoding's quality
++i;
temp.setQuality(properties[i]);
}
}
// If there is a leftover complete encoding, add it.
if(temp != null && temp.isComplete())
{
encodingList.addElement( temp );
}
// Convert the Vector to an array for later use
_encodings = new EncodingProperties[ encodingList.size() ];
encodingList.copyInto((Object[])_encodings);
}
catch (Exception e)
{
// Something is wrong, indicate that there are no encoding options
_encodings = null;
home.errorDialog(e.toString());
}
}
/**
* Adds the VideoField to the screen
*/
private void createUI()
{
// Add the video field to the screen
camera_vfm.add(_videoField);
}
/**
* Create a screen used to display a snapshot
* #param raw A byte array representing an image
*/
private void createImageScreen( byte[] raw )
{
main_vfm.replace(camera_vfm, image_vfm);
fieldChanged(raw);
Bitmap image1 = Bitmap.createBitmapFromBytes( readFile(),0, -1, 5 );
try{
if(flag == 1){
}
else{
image_vfm.delete(imageField);
}
imageField.setBitmap(image1);
image_vfm.add(imageField);
}
catch(Exception e){System.out.println(e.toString());}
}
private byte[] readFile() {
byte[] result = null;
FileConnection fconn = null;
try {
fconn = (FileConnection)Connector.open(FILE_NAME + "_front" + EXTENSION);
} catch (IOException e) {
System.out.print("Error opening file");
}
if (!fconn.exists()) {
//Dialog.inform("file not exist");
} else {
InputStream in = null;
ByteVector bytes = new ByteVector();
try {
in = fconn.openInputStream();
} catch (IOException e) {
System.out.print("Error opening input stream");
}
try {
int c = in.read();
while (-1 != c) {
bytes.addElement((byte) c);
c = in.read();
}
result = bytes.getArray();
} catch (IOException e) {
System.out.print("Error reading input stream");
}
try {
fconn.close();
} catch (IOException e) {
System.out.print("Error closing file");
}
}
return result;
}
public void fieldChanged( final byte[] _raw )
{
try
{
flag ++;
// Create the connection to a file that may or
// may not exist.
FileConnection file = (FileConnection)Connector.open(FILE_NAME + "_front" + EXTENSION);
// If the file exists, increment the counter until we find
// one that hasn't been created yet.
if (file.exists()) {
file.delete();
file.close();
file = (FileConnection) Connector.open(FILE_NAME + "_front" + EXTENSION);
}
//FileConnection file_temp = (FileConnection)Connector.open(FILE_NAME + "tempimg" + EXTENSION);
//file_temp.delete();
// We know the file doesn't exist yet, so create it
file.create();
// Write the image to the file
OutputStream out = file.openOutputStream();
out.write(_raw);
// Close the connections
//out.close();
file.close();
//Dialog.inform( "Saved to " + FILE_NAME + "_front" + EXTENSION );
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
Dialog.inform( "File not saved this time");
}
}
/**
* Sets the index of the encoding in the 'encodingList' Vector
* #param index The index of the encoding in the 'encodingList' Vector
*/
public void setIndexOfEncoding(int index)
{
_indexOfEncoding = index;
}
/**
* #see net.rim.device.api.ui.Screen#invokeAction(int)
*/
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if(!handled)
{
switch(action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
srn2 screen2 = new srn2();
srn3 screen3 = new srn3();
srn4 screen4 = new srn4();
if(field==bt)
{
main_vfm.replace(image_vfm, camera_vfm);
}
if(field==back_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen2);
}
if(field==side1_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen3);
}
if(field==side2_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen4);
}
}
}
Note: This Error displaying first "javax.microedition.media.MediaException: There is already another active Player. Call Player.close() on the existing Player to free up the resources." and camera gets open and when i try to take picture this error displays "Error Class Java.lang.ArrayIndexOutOfBoundsException: Index 0>=0"
After _videoControl.getSnapshot( encoding ) has been called you need to close player (i.e. to call player.close(). And that's exactly what the exception tells about.
However this method of taking images is highly unreliable - you'll not be able to use it for every BB device model. I don't know why RIM put it in SDK samples. By doing that RIM pushes developers to a wrong way. As alishaik786 mentiones a proper method of taking images on BB is using Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA, new CameraArguments()) with a FileSystemJournalListener implementation. Just search on StackOverflow on these for the implementation details. I vaguely recall the implementation is painful (like many other parts on BB), but once done it will work on any device.
you got two error
1."javax.microedition.media.MediaException: There is already another active Player. Call Player.close()
this exception thrown if you try to open camera (player) while another instance of camera is already opened. In your code, you need to define the player object as a class level and must close the player after taking the snapshot (also need to close the player if you push from one screen to another).
2."Error Class Java.lang.ArrayIndexOutOfBoundsException: Index 0>=0"
This error may occur when you access encoding array while encoding array size is zero.
You can ensure this issue by using _videoControl.getSnapshot( null), which take the snapshot in default encoding.
So first insure these issue and reply me.

How to handle add request in smack API

I use Smack API to write my Google talk Client . Now i need to handle add request for this .
I set SubscriptionMode to manual & now I have to registering a listener for presence packets but i don't know how !!
can any body help ?
I have not tried it yet, but I guess the below should work. If using the manual mode, a PacketListener should be registered that listens for Presence packets that have a type of Presence.Type.subscribe.
First set the roster:
Roster roster = connection.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
Then add a packet listner to the above connection, eg :
connection.addPacketListener(new SubscriptionListener(), new PacketFilter(){
public boolean accept(Packet packet) {
if(packet instanceof Presence)
if(((Presence)packet).getType().equals(Presence.Type.subscribe))
return true;
return false;
}});
The above code just returns true for all requests, But you can customize it i.e set it to true or false based on user GUI input.
public static void admitFriendsRequest() {
connection.getRoster().setSubscriptionMode(
Roster.SubscriptionMode.manual);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet paramPacket) {
System.out.println("\n\n");
if (paramPacket instanceof Presence) {
Presence presence = (Presence) paramPacket;
String email = presence.getFrom();
System.out.println("chat invite status changed by user: : "
+ email + " calling listner");
System.out.println("presence: " + presence.getFrom()
+ "; type: " + presence.getType() + "; to: "
+ presence.getTo() + "; " + presence.toXML());
Roster roster = connection.getRoster();
for (RosterEntry rosterEntry : roster.getEntries()) {
System.out.println("jid: " + rosterEntry.getUser()
+ "; type: " + rosterEntry.getType()
+ "; status: " + rosterEntry.getStatus());
}
System.out.println("\n\n\n");
if (presence.getType().equals(Presence.Type.subscribe)) {
Presence newp = new Presence(Presence.Type.subscribed);
newp.setMode(Presence.Mode.available);
newp.setPriority(24);
newp.setTo(presence.getFrom());
connection.sendPacket(newp);
Presence subscription = new Presence(
Presence.Type.subscribe);
subscription.setTo(presence.getFrom());
connection.sendPacket(subscription);
} else if (presence.getType().equals(
Presence.Type.unsubscribe)) {
Presence newp = new Presence(Presence.Type.unsubscribed);
newp.setMode(Presence.Mode.available);
newp.setPriority(24);
newp.setTo(presence.getFrom());
connection.sendPacket(newp);
}
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
if (packet instanceof Presence) {
Presence presence = (Presence) packet;
if (presence.getType().equals(Presence.Type.subscribed)
|| presence.getType().equals(
Presence.Type.subscribe)
|| presence.getType().equals(
Presence.Type.unsubscribed)
|| presence.getType().equals(
Presence.Type.unsubscribe)) {
return true;
}
}
return false;
}
});
connection.getRoster().addRosterListener(new RosterListener() {
public void presenceChanged(Presence presence) {
System.out.println(presence.getFrom() + "presenceChanged");
}
public void entriesUpdated(Collection<String> presence) {
System.out.println("entriesUpdated");
}
public void entriesDeleted(Collection<String> presence) {
System.out.println("entriesDeleted");
}
public void entriesAdded(Collection<String> presence) {
System.out.println("entriesAdded");
}
});
}

Resources