How to properly update Android BillingFlowParams sku() to setSkuDetails() - in-app-purchase

here is the code can anyone tell how can I setSkuDetails()
as I was using vision one now I update it to 4
However, setSku and setType seem to be deprecated in the BillingFlowParams.Builder class. Instead, we should be using setSkuDetails(SkuDetails).
private void BillingFunction() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Establish connection to billing client
mBillingClient = BillingClient.newBuilder(MainActivity.this).setListener(MainActivity.this).build();
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// The billing client is ready. You can query purchases here.
getPricesMonthlyTime();
getPricesYearlyTime();
getPricesONeTime();
}
}
#Override
public void onBillingServiceDisconnected() {
//TODO implement your own retry policy
Toast.makeText(MainActivity.this, getResources().getString(R.string.billing_connection_failure), Toast.LENGTH_SHORT);
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
continue_button.setOnClickListener(view -> {
if (select_radio_one.getVisibility() == View.VISIBLE) {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails()
.build();
BillingResult responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
brandDialogInAppPurchase.dismiss();
} else if (select_radio_two.getVisibility() == View.VISIBLE) {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails()
.build();
BillingResult responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
brandDialogInAppPurchase.dismiss();
} else if (select_radio_three.getVisibility() == View.VISIBLE) {
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails()
.build();
BillingResult responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
brandDialogInAppPurchase.dismiss();
} else {
Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
// queryPrefPurchases();
queryPurchases();
}

You should send the object skuDetail.
To do so you need to retrieve it by calling querySkuDetailsAsync().
fun querySkuDetails() {
val skuList = ArrayList<String>()
skuList.add("premium_upgrade")
skuList.add("gas")
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(SkuType.INAPP)
// leverage querySkuDetails Kotlin extension function
val skuDetailsResult = withContext(Dispatchers.IO) {
billingClient.querySkuDetails(params.build())
}
// Process the result.
}

Related

How fix this null check issue?

Dart Language:
This is plugin issue
xmpp_stone plugin
I can't fix this issue
anyone known please replay
[![enter image description here]
https://i.stack.imgur.com/FHe0O.png
Dart Language:
This is plugin issue
xmpp_stone plugin
I can't fix this issue
anyone known please replay
[![enter image description here]
https://i.stack.imgur.com/FHe0O.png
This is full code issue in xmpp_stone plugin
import 'dart:io';
import 'package:xmpp_stone/src/logger/Log.dart';
import 'package:console/console.dart';
import 'dart:async';
import 'dart:convert';
import 'package:xmpp_stone/xmpp_stone.dart' as xmpp;
import 'package:image/image.dart' as image;
final String TAG = 'example';
class ExampleConnectionStateChangedListener implements xmpp.ConnectionStateChangedListener {
late xmpp.Connection _connection;
late xmpp.MessagesListener _messagesListener;
StreamSubscription<String>? subscription;
ExampleConnectionStateChangedListener(xmpp.Connection connection, xmpp.MessagesListener messagesListener) {
_connection = connection;
_messagesListener = messagesListener;
_connection.connectionStateStream.listen(onConnectionStateChanged);
}
#override
void onConnectionStateChanged(xmpp.XmppConnectionState state) {
if (state == xmpp.XmppConnectionState.Ready) {
Log.d(TAG, 'Connected');
_connection.getMamModule().queryAll();
var vCardManager = xmpp.VCardManager(_connection);
vCardManager.getSelfVCard().then((vCard) {
if (vCard != null) {
Log.d(TAG, 'Your info' + vCard.buildXmlString());
}
});
var messageHandler = xmpp.MessageHandler.getInstance(_connection);
var rosterManager = xmpp.RosterManager.getInstance(_connection);
messageHandler.messagesStream.listen(_messagesListener.onNewMessage);
sleep(const Duration(seconds: 1));
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
rosterManager.addRosterItem(xmpp.Buddy(receiverJid)).then((result) {
if (result.description != null) {
print("TAG, 'add roster'" + result.description!);
}
});
sleep(const Duration(seconds: 1));
vCardManager.getVCardFor(receiverJid).then((vCard) {
if (vCard != null) {
print("TAG, 'Receiver info'" + vCard.buildXmlString());
if (vCard != null && vCard.image != null) {
var file = File('test456789.jpg')..writeAsBytesSync(image.encodeJpg(vCard.image!));
print("TAG, IMAGE SAVED TO: ${file.path}");
}
}
});
var presenceManager = xmpp.PresenceManager.getInstance(_connection);
presenceManager.presenceStream.listen(onPresence);
}
}
void onPresence(xmpp.PresenceData event) {
Log.d(TAG, 'presence Event from ' + event.jid!.fullJid! + ' PRESENCE: ' + event.showElement.toString());
}
}
Stream<String> getConsoleStream() {
return Console.adapter.byteStream().map((bytes) {
var str = ascii.decode(bytes);
str = str.substring(0, str.length - 1);
return str;
});
}
class ExampleMessagesListener implements xmpp.MessagesListener {
#override
void onNewMessage(xmpp.MessageStanza? message) {
if (message!.body != null) {
Log.d(TAG ,format(
'New Message from {color.blue}${message.fromJid!.userAtDomain}{color.end} message: {color.red}${message.body}{color.end}'));
}
}
#override
void onChatMessage(xmpp.MessageStanza? message) {
print(message);
if (message!.body != null) {
Log.d(TAG,format(
'New Message from {color.blue}${message.fromJid!.userAtDomain}{color.end} message: {color.red}${message.body}{color.end}'));
}
}
}
sendmessageforxmpp(){
var userAtDomain = 'xxx#gmail.com';
var password = 'password';
var jid = xmpp.Jid.fromFullJid(userAtDomain);
var account = xmpp.XmppAccountSettings(userAtDomain, jid.local,
jid.domain, password, 5222, resource: 'xmppstone');
var connection = xmpp.Connection(account);
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
Log.d(TAG, receiverJid.fullJid.toString());
var messageHandler =
xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
}
Your problem is that you are not using xmpp_stone correctly and therefore ends up in a situation where the internal state of xmpp_stone does not match what the developer of the package have intended.
I do, however, think the package are badly designed in such a way that wrong usage are very likely to happen so I would not blame you for getting into trouble.
The problem is the following in your code:
var connection = xmpp.Connection(account);
// ..
var messageHandler = xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
You are here creating a Connection but the underlying socket are never created. The default value for the internal state of Connection are XmppConnectionState.Idle. But when you are later trying to sendMessage, your code ends up running this from the package:
void write(message) {
Log.xmppp_sending(message);
if (isOpened()) {
_socket!.write(message);
}
}
bool isOpened() {
return state != XmppConnectionState.Closed &&
state != XmppConnectionState.ForcefullyClosed &&
state != XmppConnectionState.Closing &&
state != XmppConnectionState.SocketOpening;
}
The isOpened() ends up returning true since it sees XmppConnectionState.Idle as an open state where messages are allowed to be sent.
But that is not the case here since we never asked Connection to open actually do any connection and therefore _socket ends up being null. Since the package are trying to do ! on null, the application crashes.
For an actual solution, we can get inspired from the example implementation from xmpp_dart:
https://github.com/vukoye/xmpp_dart/blob/master/example/example.dart
We can here see they have a connection.connect(); call. But, I am going to guess this really only works because the example are not going to use the connection right after this call. The problem is that it is implemented like the following:
void connect() {
if (_state == XmppConnectionState.Closing) {
_state = XmppConnectionState.WouldLikeToOpen;
}
if (_state == XmppConnectionState.Closed) {
_state = XmppConnectionState.Idle;
}
if (_state == XmppConnectionState.Idle) {
openSocket();
}
}
Future<void> openSocket() async {
connectionNegotatiorManager.init();
setState(XmppConnectionState.SocketOpening);
try {
return await Socket.connect(account.host ?? account.domain, account.port)
.then((Socket socket) {
// if not closed in meantime
if (_state != XmppConnectionState.Closed) {
setState(XmppConnectionState.SocketOpened);
So connect() returns void but calls openSocket() which does return a Future that would be able to tell us when the connection are actually ready.
I would therefore instead suggest using openSocket() directly and make your sendmessageforxmpp() method async so we can await on the connection being open.
So your code should look like:
Future<void> sendmessageforxmpp() async {
var userAtDomain = 'xxx#gmail.com';
var password = 'password';
var jid = xmpp.Jid.fromFullJid(userAtDomain);
var account = xmpp.XmppAccountSettings(
userAtDomain, jid.local, jid.domain, password, 5222,
resource: 'xmppstone');
var connection = xmpp.Connection(account);
await connection.openSocket(); // <--- the important change :)
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
Log.d(TAG, receiverJid.fullJid.toString());
var messageHandler = xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
}
This error is usually occurring when you use the bang operator (!) on a nullable value that was not properly initialized, like
yourvariable!.somefield
The above assumes that yourvariable will not be null as this point. If it's null, then reality is in conflict with the assumption I have just described.

AWS transcribe Unable to load credentials from any of the providers in the chain AwsCredentialsProviderChain

I am running a java program that uses AWS TranscribeStreaming. I have created(from AWS console) and downloaded AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY then set the environment variables.
When I run the program I am getting error message:
Unable to load credentials from any of the providers in the chain AwsCredentialsProviderChain.
I don't why but this error was also occurring while using Google SDK for speech recognition.
here is the code I am trying to run.
public class TranscribeStreamingDemoApp {
private static final Region REGION = Region.US_WEST_2;
private static TranscribeStreamingAsyncClient client;
public static void main(String args[]) throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException {
client = TranscribeStreamingAsyncClient.builder()
.credentialsProvider(getCredentials())
.region(REGION)
.build();
CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000),
new AudioStreamPublisher(getStreamFromMic()),
getResponseHandler());
result.get();
client.close();
}
private static InputStream getStreamFromMic() throws LineUnavailableException {
// Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
int sampleRate = 16000;
AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line not supported");
System.exit(0);
}
TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
InputStream audioStream = new AudioInputStream(line);
return audioStream;
}
private static AwsCredentialsProvider getCredentials() {
return DefaultCredentialsProvider.create();
}
private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) {
return StartStreamTranscriptionRequest.builder()
.languageCode(LanguageCode.FR_FR.toString())
.mediaEncoding(MediaEncoding.PCM)
.mediaSampleRateHertz(mediaSampleRateHertz)
.build();
}
private static StartStreamTranscriptionResponseHandler getResponseHandler() {
return StartStreamTranscriptionResponseHandler.builder()
.onResponse(r -> {
System.out.println("Received Initial response");
})
.onError(e -> {
System.out.println(e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("Error Occurred: " + sw.toString());
})
.onComplete(() -> {
System.out.println("=== All records stream successfully ===");
})
.subscriber(event -> {
List<software.amazon.awssdk.services.transcribestreaming.model.Result> results = ((TranscriptEvent) event).transcript().results();
if (results.size() > 0) {
if (!results.get(0).alternatives().get(0).transcript().isEmpty()) {
System.out.println(results.get(0).alternatives().get(0).transcript());
}
}
})
.build();
}
private InputStream getStreamFromFile(String audioFileName) {
try {
File inputFile = new File(getClass().getClassLoader().getResource(audioFileName).getFile());
InputStream audioStream = new FileInputStream(inputFile);
return audioStream;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
private static class AudioStreamPublisher implements Publisher<AudioStream> {
private final InputStream inputStream;
private static Subscription currentSubscription;
private AudioStreamPublisher(InputStream inputStream) {
this.inputStream = inputStream;
}
#Override
public void subscribe(Subscriber<? super AudioStream> s) {
if (this.currentSubscription == null) {
this.currentSubscription = new SubscriptionImpl(s, inputStream);
} else {
this.currentSubscription.cancel();
this.currentSubscription = new SubscriptionImpl(s, inputStream);
}
s.onSubscribe(currentSubscription);
}
}
public static class SubscriptionImpl implements Subscription {
private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1;
private final Subscriber<? super AudioStream> subscriber;
private final InputStream inputStream;
private ExecutorService executor = Executors.newFixedThreadPool(1);
private AtomicLong demand = new AtomicLong(0);
SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) {
this.subscriber = s;
this.inputStream = inputStream;
}
#Override
public void request(long n) {
if (n <= 0) {
subscriber.onError(new IllegalArgumentException("Demand must be positive"));
}
demand.getAndAdd(n);
executor.submit(() -> {
try {
do {
ByteBuffer audioBuffer = getNextEvent();
if (audioBuffer.remaining() > 0) {
AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
subscriber.onNext(audioEvent);
} else {
subscriber.onComplete();
break;
}
} while (demand.decrementAndGet() > 0);
} catch (Exception e) {
subscriber.onError(e);
}
});
}
#Override
public void cancel() {
executor.shutdown();
}
private ByteBuffer getNextEvent() {
ByteBuffer audioBuffer = null;
byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];
int len = 0;
try {
len = inputStream.read(audioBytes);
if (len <= 0) {
audioBuffer = ByteBuffer.allocate(0);
} else {
audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return audioBuffer;
}
private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
return AudioEvent.builder()
.audioChunk(SdkBytes.fromByteBuffer(bb))
.build();
}
}
}
Finally, I solved the problem, the documentation specifies that:
AWS credentials provider chain that looks for credentials in this order:
1.Java System Properties - aws.accessKeyId and aws.secretAccessKey
2.Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
3.Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI
Since setting up through environment variables didn't work, I opted to set credentials with Java system properties and it works!
Doc ref: https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/DefaultCredentialsProvider.html
System.setProperty("aws.accessKeyId", "**************");
System.setProperty("aws.secretAccessKey", "**************");

Azure Mobile Service calls hangs

Using Xamarin.Forms app. When mobile data connection fluctuates on Android devices, e.g. network from 3G to 2G connection, or vice versa - the call seems to get hung somewhere.
This is the Azure API call :
public Task<ObservableCollection<Models.Item>> GetItemsByID(string tenantID, string auth_token)
{
return Task.Factory.StartNew(() =>
{
var res = RestClient.Get<ObservableCollection<Models.Item>>(HttpWebRequest.Create(string.Format(EndPointsList.GetItemsUrl + "tenantID={0}", tenantID)),auth_token);
return res ;
});
}
We initiate the System.Net.WebRequest here :
public static T Get<T>(WebRequest request, string auth_token, string requestData = null)
{
string result = string.Empty;
request.ContentType = "application/json";
request.Headers["ZUMO-API-VERSION"] = "2.0.0";
if (auth_token.StartsWith("Bearer"))
request.Headers["Authorization"] = auth_token;
else {
request.Headers["x-access_type"] = "offline";
request.Headers["x-zumo-auth"] = auth_token;
}
try
{
WebResponse webResponse = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null).Result;
using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
var typ = typeof(T);
if (
typ == typeof(String)
|| typ == typeof(float)
|| typ == typeof(Decimal)
|| typ == typeof(Int16)
|| typ == typeof(Int32)
|| typ == typeof(Int64)
)
{
return (T)Convert.ChangeType(result, typeof(T), null);
}
return result.FromJson<T>();
}
catch (AggregateException agEx)
{
AggregateException(agEx);
return result.FromJson<T>();
}
catch (Exception ex)
{
return result.FromJson<T>();
}
}
This is the call from ViewModel
public async Task GetAllItems()
{
try
{
if (!this.IsInternetConnectionAvailable())
{
await this.CurrentContentPage.DisplayAlert("", AppResources.InternetConnectionNotAvailable, AppResources.Ok);
return;
}
this.ProgressBar.ShowProgress(AppResources.Loading);
ItemList = await this.ItemService.GetItemsByID(App.Locator.Login.LoggedInUser.TenantID.ToString(),Settings.AuthToken);
if (ItemList != null)
{
for (int i = 0; i < this.ItemList.Count; i++)
{
ItemList[i].RowColor = (i % 2 == 0 ? Theme.EvenRowColor : Theme.OddRowColor);
}
}
RaisePropertyChanged("ItemList");
}
catch (Exception ex)
{
ExceptionHandler.HandleException(CurrentContentPage, ex);
}
finally
{
this.ProgressBar.Dismiss();
}
}
In actual case here - the ProgressBar will kept on be displayed on the device, though its in Finally block. User have to kill the application to make it work again.
And we're unsuccessful to reproduce this back in lab. It only happens on field during intermittent connections.
Any abnormalities in the code? If not, how can we capture this in application log.

How make my own Stream

I have already try to understand the API doc, the articles about them, and this post: How do you create a Stream in Dart
I'm making a simple web app using WebSocket. Actually, it's working well, but I want add a feature (enjoy learn).
This is my class (can be optimized I guess)
library Ask;
import 'dart:html';
import 'dart:async';
import 'dart:convert';
class Ask {
final String addr;
String _protocol;
String _port;
WebSocket _ws;
bool openned;
Map<int, Completer> _completer_list = {};
int _counter = 0;
static final Map<String, Ask> _cache = <String, Ask>{};
factory Ask(String addr) {
if (_cache.containsKey(addr)) {
return _cache[addr];
} else {
final ask_server = new Ask._internal(addr);
_cache[addr] = ask_server;
return ask_server;
}
}
Ask._internal(this.addr);
Future<bool> open() {
if (openned)
return true;
_completer_list[0] = new Completer();
if (window.location.protocol == 'http:') {
_port = ':8080/ws';
_protocol = 'ws://';
} else {
_port = ':8443/ws';
_protocol = 'wss://';
}
_ws = new WebSocket(_protocol + addr + _port);
_ws.onOpen.listen((e) {
_get_data();
_get_close();
openned = true;
_completer_list[0].complete(true);
});
return _completer_list[0].future;
}
Future<String> send(Map data) {
bool check = false;
int id;
_completer_list.forEach((k, v) {
if (v.isCompleted) {
id = data['ws_id'] = k;
_completer_list[k] = new Completer();
_ws.send(JSON.encode(data));
check = true;
}
});
if (!check) {
_counter++;
id = data['ws_id'] = _counter;
_completer_list[id] = new Completer();
_ws.send(JSON.encode(data));
}
return _completer_list[id].future;
}
void _get_data() {
_ws.onMessage.listen((MessageEvent data) {
var response = JSON.decode(data.data);
_completer_list[response['ws_id']].complete(response);
});
}
void _get_close() {
_ws.onClose.listen((_) {
print('Server have been lost. Try to reconnect in 3 seconds.');
new Timer(new Duration(seconds: 3), () {
_ws = new WebSocket(_protocol + addr + _port);
_get_data();
_get_close();
_ws.onOpen.listen((e) => print('Server is alive again.'));
});
});
}
}
Example of use:
void showIndex() {
Element main = querySelector('main');
Ask connect = new Ask('127.0.0.1');
Map request = {};
request['index'] = true;
connect.open().then((_) {
connect.send(request).then((data) {
main.setInnerHtml(data['response']);
});
});
}
I would replace the then by a listen who will be canceled when the message will completed. By this way, I can add a progress bar, I think...
So my question, my send function can be a stream and keep my concept of one websocket for all ? (yes, if my function is used when a request is in progress, it's sent and if she's finish before the first, I recovered her properly. Thank you ws_id).
Thank you.
I think what you need is a StreamController
https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-async.StreamController

Blackberry App is working on wi-fi but not on Packet Data/GPRS

I have created Blackberry Application which is working perfectly fine on wi-fi. But when I turn off wi-fi and use Mobile Network then I am not able to run application. It shows No Internet connection available.
I had written these lines.
if (DeviceInfo.isSimulator())
{
deviceinfo = deviceinfo.concat(";deviceside=true");
}
Here is My Http Connection Class
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
public class HttpConn
{
public String jsonresponse (String url)
{
String response = null;
HttpConnection httpConnection = null;
InputStream inStream = null;
int code;
StringBuffer stringBuffer = new StringBuffer();
String deviceinfo=url;
try
{
if (DeviceInfo.isSimulator())
{
deviceinfo = deviceinfo.concat(";deviceside=true");
}
/* else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
deviceinfo = ";interface=wifi";
}*/
else if ( (RadioInfo.getActiveWAFs() & RadioInfo.WAF_WLAN) != 0 && RadioInfo.getSignalLevel( RadioInfo.WAF_WLAN ) != RadioInfo.LEVEL_NO_COVERAGE )
{
deviceinfo = deviceinfo.concat(";interface=wifi");
}
// else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
// {
// deviceinfo = ";interface=wifi";//
// }
if ( (RadioInfo.getActiveWAFs() & RadioInfo.WAF_WLAN) != 0 && RadioInfo.getSignalLevel( RadioInfo.WAF_WLAN ) != RadioInfo.LEVEL_NO_COVERAGE )
{
deviceinfo = deviceinfo.concat(";interface=wifi");
}
// 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
//
// deviceinfo = ";deviceside=true";
//
// }
// else
// {
// // otherwise, use the Uid to construct a valid carrier BIBS
// // request
//
// deviceinfo = ";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)
// {
//
// deviceinfo = ";deviceside=false";
//
// }
//
// // If there is no connection available abort to avoid hassling the user
// // unnecssarily.
// else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
// {
// deviceinfo = "none";
//
//
// }
// else
// {
// deviceinfo=";deviceside=true";
// }
//if(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT,RadioInfo.WAF_WLAN,false))
// httpConnection = (HttpConnection) Connector.open(url+";interface=wifi", Connector.READ);
httpConnection = (HttpConnection) Connector.open(deviceinfo, Connector.READ);
httpConnection.setRequestMethod(HttpConnection.GET);
code = httpConnection.getResponseCode();
if(code == HttpConnection.HTTP_OK)
{
inStream=httpConnection.openInputStream();
int c;
while((c=inStream.read())!=-1)
{
stringBuffer.append((char)c);
}
response=stringBuffer.toString();
System.out.println("Response Getting from Server is ================" + response);
}
// Is the carrier network the only way to connect?
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.inform("Connection error");
}
});
}
// return deviceinfo;
}
catch (Exception e)
{
System.out.println("caught exception in jsonResponse method"+e.getMessage());
}
finally
{
// if (outputStream != null)
// {
// outputStream.close();
// }
if (inStream != null)
{
try
{
inStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (httpConnection != null )
{
try
{
httpConnection.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
// private synchronized 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;
// }
}
Actually solution is found.
java.io.IOException:APN is not specified . what APN i have to set manually to device for Wi-Fi network?
http://m2m.icpdas.com/download/gtm-201_modem/manual/gprs_apn.pdf
http://www.faqspedia.com/list-of-all-indian-mobile-operators-access-point-names
Refer this link.
Actually we have to set APN manually. We get it from the Provider.
I hope someone get solution from my this answer. Thanks a lot for your support.

Resources