how to zip in rxjava - multithreading

Hi I'm a newbie with RXJava,I am trying to work on my first RxJava example that like below
Observable<String> myObservable = Observable.create(
new Observable.OnSubscribe<String>() {
public void call(Subscriber<? super String> subscriber) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
subscriber.onNext("hello world");
subscriber.onCompleted();
}
}
).subscribeOn(Schedulers.computation());
Observable<String> myObservable1 = Observable.just("thank you");
Observable observable3 = Observable.zip(myObservable, myObservable1, new Func2<String,String,String>() {
#Override
public String call(String o, String o2) {
return o+":"+o2;
}
});
observable3.subscribe(new Action1<String>() {
#Override
public void call(String o) {
System.out.println("before");
System.out.println(o);
}
});
System.out.println("after");
I want to print before then after,how I to do that with rxjava and without sleep

One possible way:
Observable<String> myObservable = Observable.create(
new Observable.OnSubscribe<String>() {
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("hello world");
subscriber.onCompleted();
}
}
).subscribeOn(Schedulers.computation());
Observable<String> myObservable1 = Observable.just("thank you");
Observable observable3 = Observable.zip(myObservable, myObservable1, new Func2<String,String,String>() {
#Override
public String call(String o, String o2) {
return o+":"+o2;
}
});
Observable.just("before").concatWith(observable3).concatWith(Observable.just("after")).toBlocking().subscribe(new Action1<String>() {
#Override
public void call(String s) {
System.out.println(s);
}
});
Result is:
before
hello world:thank you
after

Related

Trouble with logic flow for filtering search method on CS50 Pokedex

The app compiles fine but initially it shows nothing in the list. When I use the search bar, it doesn't display my filtered information and when I get rid of search, the entire list is finally display. Any help would be really appreciated, this is my first time ever coding in Java.
Here is my adapter code.
public class PokedexAdapter extends RecyclerView.Adapter<PokedexAdapter.PokedexViewHolder> implements Filterable {
public static class PokedexViewHolder extends RecyclerView.ViewHolder {
public LinearLayout containerView;
public TextView textView;
PokedexViewHolder(View view) {
super(view);
containerView = view.findViewById(R.id.pokedex_row);
textView = view.findViewById(R.id.pokedex_row_text_view);
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pokemon current = (Pokemon) containerView.getTag();
Intent intent = new Intent(v.getContext(), PokemonActivity.class);
intent.putExtra("name", current.getName());
intent.putExtra("url", current.getUrl());
v.getContext().startActivity(intent);
}
});
}
}
private List<Pokemon> pokemon = new ArrayList<>();
private RequestQueue requestQueue;
private List<Pokemon> filteredPokemon = new ArrayList<>();
PokedexAdapter(Context context) {
requestQueue = Volley.newRequestQueue(context);
loadPokemon();
}
public void loadPokemon() {
String url = "https://pokeapi.co/api/v2/pokemon?limit=365";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String name = result.getString("name");
pokemon.add(new Pokemon(
name.substring(0, 1).toUpperCase() + name.substring(1),
result.getString("url")
));
}
notifyDataSetChanged();
} catch (JSONException e) {
Log.e("cs50", "Json error", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("cs50", "Pokemon list error");
}
});
requestQueue.add(request);
}
#NonNull
#Override
public PokedexViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.pokedex_row, parent, false);
return new PokedexViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PokedexViewHolder viewholder, int position){
Pokemon results = pokemon.get(position);
viewholder.textView.setText(results.getName());
viewholder.containerView.setTag(results);
}
#Override
public int getItemCount() {
return filteredPokemon.size();
}
#Override
public Filter getFilter() {
return new PokemonFilter();
}
private class PokemonFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// implement your search here
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
//No filter implemented return whole list
results.values = pokemon;
results.count = pokemon.size();
}
else {
List<Pokemon> filtered = new ArrayList<>();
for (Pokemon pokemon : filtered) {
if (pokemon.getName().toUpperCase().startsWith(constraint.toString())) {
filtered.add(pokemon);
}
}
results.values = filtered;
results.count = filtered.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredPokemon = (List<Pokemon>) results.values;
notifyDataSetChanged();
}
}
}
I really am not sure what is going on and given my knowledge of the subject, you could really help with understanding the logic better. Please let me know if there is any other information you would like from me about the code.
You might have already solved it and finished the Android tracks but this was the only thing I changed and it seemed to work after that.
for (Pokemon pokemon : pokemon) {
if (pokemon.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()) {
filtered.add(pokemon);
}
}

Android Studio In App Billing How To Verify Purchase On Device?

I've been working with Android Studio for a short time and this is my first project. I don't know a lot of points, and I apologize for my complex code. There are only 1 consumable product in my app and gives the user 20 lives. I succeeded in adding in-app purchase to my application as a result of long efforts. In my application I was able to make purchases with google test cards with my own product ID. I did not have any problems up to here. Since I don't have a server, I have to do the purchase verification on the device. I wrote all purchase and verification codes in an activity. I think it might sound a bit silly, but I don't know where to make the confirmation of the purchase. My application accepts verification even if it is an incorrect signature. What is the point I missed in my codes?
public class MagazaActivity extends AppCompatActivity {
Button baslik, buy_button;
Can hak;
int can;
private BillingClient mBillingClient;
private final List<Purchase> mPurchases = new ArrayList<>();
private static final String BASE_64_ENCODED_PUBLIC_KEY = "XXXXX";
private static final String TAG = "IABUtil/Security";
private static final String KEY_FACTORY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
String canfiyat;
mBillingClient =BillingClient.newBuilder(MagazaActivity.this).
setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated ( int responseCode,
#Nullable List<Purchase> purchases){
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for (final Purchase purchase : purchases) {
ConsumeResponseListener listener = new
ConsumeResponseListener() {
#Override
public void
onConsumeResponse(#BillingClient.BillingResponse int responseCode, String
outToken) {
if (responseCode ==
BillingClient.BillingResponse.OK) {
handlePurchase(purchase);
}
}
};
mBillingClient.consumeAsync(purchase.getPurchaseToken(), listener);
}
} else if (responseCode ==
BillingClient.BillingResponse.USER_CANCELED) {
billingCanceled();
}
else {
AlertDialog.Builder builder2 = new
AlertDialog.Builder(MagazaActivity.this, R.style.AlertDialogCustom);
builder2.setMessage("Billing System İs İnvalid");
builder2.setCancelable(true);
LayoutInflater factory =
LayoutInflater.from(MagazaActivity.this);
final View view = factory.inflate(R.layout.sample4,
null);
builder2.setView(view);
builder2.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder2.create();
alert11.show();
}
}
}).
build();
buy_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.startConnection(new BillingClientStateListener()
{
#Override
public void
onBillingSetupFinished(#BillingClient.BillingResponse int
billingResponseCode) {
if (billingResponseCode ==
BillingClient.BillingResponse.OK) {
final List<String> skuList = new ArrayList<>();
skuList.add("XXX");
SkuDetailsParams skuDetailsParams =
SkuDetailsParams.newBuilder()
.setSkusList(skuList).setType(BillingClient.SkuType.INAPP).build();
mBillingClient.querySkuDetailsAsync(skuDetailsParams,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int
responseCode,
List<SkuDetails> skuDetailsList) {
BillingFlowParams flowParams =
BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(0))
.build();
int billingResponseCode =
mBillingClient.launchBillingFlow(MagazaActivity.this, flowParams);
if (billingResponseCode ==
BillingClient.BillingResponse.OK) {
for (SkuDetails skuDetails :
skuDetailsList) {
String sku =
skuDetails.getSku();
String price =
skuDetails.getPrice();
if ("XXX".equals(sku)) {
canfiyat = price;
}
}
}
}
});
}
}
#Override
public void onBillingServiceDisconnected() {
AlertDialog.Builder builder = new
AlertDialog.Builder(MagazaActivity.this);
builder.setMessage("Connection Error")
.setCancelable(false)
.setPositiveButton("Retry", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
#Override
public void onBackPressed() {
Intent intentLayout8 = new Intent(MagazaActivity.this,
MainActivity.class);
startActivity(intentLayout8);
MagazaActivity.this.finish();
}
private void billingCanceled() {
AlertDialog.Builder builder = new
AlertDialog.Builder(MagazaActivity.this);
builder.setMessage("Purchase Canceled")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey,
Base64.DEFAULT);
KeyFactory keyFactory =
KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new
X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
}
}
public static boolean verifyPurchase(String base64PublicKey, String
signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey)
||
TextUtils.isEmpty(signature)) {
Log.e("HATA", "Purchase verification failed");
return false;
}
PublicKey key = MagazaActivity.generatePublicKey(base64PublicKey);
return MagazaActivity.verify(key, signedData, signature);
}
public static boolean verify(PublicKey publicKey, String signedData, String
signature) {
byte[] signatureBytes;
try {
signatureBytes = Base64.decode(signature, Base64.DEFAULT);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Base64 decoding failed.");
return false;
}
try {
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(signatureBytes)) {
Log.e(TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "NoSuchAlgorithmException.");
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key specification.");
} catch (SignatureException e) {
Log.e(TAG, "Signature exception.");
}
return false;
}
private boolean verifyValidSignature(String signedData, String signature) {
try {
return MagazaActivity.verifyPurchase(BASE_64_ENCODED_PUBLIC_KEY,
signedData, signature);
} catch (Exception e) {
Log.e(TAG, "Got an exception trying to validate a purchase: " + e);
return false;
}
}
public void handlePurchase(Purchase purchase) {
if (!verifyValidSignature(purchase.getOriginalJson(),
purchase.getSignature())) {
Log.i("Warning", "Purchase: " + purchase + "; signature
failure...");
return;
}
Log.d("MESAJ", "Got a verified purchase: " + purchase);
hak.cancan = hak.cancan + 20;
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("kalp", hak.cancan);
editor.apply();
mPurchases.add(purchase);
}
public void onResume() {
super.onResume();
}
}

spring batch job stuck in loop even when ItemReader returns null

I am converting xml to csv using spring batch and integration. I have a approach that job will start by reading files in from landing dir. while processing it will move files in inprocess dir. on error file will be moved to error dir. on successfully processing/writing file will be moved to output/completed.
After searching a while i got to know that there must be problem with itemreader but it is also returning null. I am not getting where is the problem.
Below is my batch configuration
#Bean
public Job commExportJob(Step parseStep) throws IOException {
return jobs.get("commExportJob")
.incrementer(new RunIdIncrementer())
.flow(parseStep)
.end()
.listener(listener())
.build();
}
#Bean
public Step streamStep() throws IOException {
CommReader itemReader = itemReader(null);
if (itemReader != null) {
return
steps.get("streamStep")
.<Object, Object>chunk(env.getProperty(Const.INPUT_READ_CHUNK_SIZE, Integer.class))
.reader(itemReader)
.processor(itemProcessor())
.writer(itemWriter(null))
.listener(getChunkListener())
.build();
}
return null;
}
#Bean
#StepScope
public ItemWriter<Object> itemWriter(#Value("#{jobParameters['outputFilePath']}") String outputFilePath) {
log.info("CommBatchConfiguration.itemWriter() : " + outputFilePath);
CommItemWriter writer = new CommItemWriter();
return writer;
}
#Bean
#StepScope
public CommReader itemReader(#Value("#{jobParameters['inputFilePath']}") String inputFilePath) {
log.info("CommBatchConfiguration.itemReader() : " + inputFilePath);
CommReader reader = new CommReader(inputFilePath);
// reader.setEncoding(env.getProperty("char.encoding","UTF-8"));
return reader;
}
#Bean
#StepScope
public CommItemProcessor itemProcessor() {
log.info("CommBatchConfiguration.itemProcessor() : Entry");
return new CommItemProcessor(ruleService);
}
CommReader.java
File inputFile = null;
private String jobName;
public CommReader(String inputFilePath) {
inputFile = new File(inputFilePath);
}
#Value("#{stepExecution}")
private StepExecution stepExecution;
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
#Override
public Object read() throws IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
if (inputFile.exists()) {
try {
builder = factory.newDocumentBuilder();
log.info("CommReader.read() :" + inputFile.getAbsolutePath());
Document document = builder.parse(inputFile);
return document;
} catch (ParserConfigurationException | SAXException | TransformerFactoryConfigurationError e) {
log.error("Exception while reading ", e);
}
}
return null;
}
#Override
public void close() throws ItemStreamException {
}
#Override
public void open(ExecutionContext arg0) throws ItemStreamException {
}
#Override
public void update(ExecutionContext arg0) throws ItemStreamException {
}
#Override
public void setResource(Resource arg0) {
}
CommItemProcessor.java
#Autowired
CommExportService ruleService;
public CommItemProcessor(CommExportService ruleService) {
this.ruleService = ruleService;
}
#Override
public Object process(Object bean) throws Exception {
log.info("CommItemProcessor.process() : Item Processor : " + bean);
return bean;
}
CommItemWriter.java
FlatFileItemWriter<byte[]> delegate;
ExecutionContext execContext;
FileOutputStream fileWrite;
File stylesheet;
StreamSource stylesource;
Transformer transformer;
List<List<?>> itemsTotal = null;
int recordCount = 0;
#Autowired
FileUtil fileUtil;
#Value("${input.completed.dir}")
String completedDir;
#Value("${input.inprocess.dir}")
String inprocessDir;
public void update(ExecutionContext arg0) throws ItemStreamException {
this.delegate.update(arg0);
}
public void open(ExecutionContext arg0) throws ItemStreamException {
this.execContext = arg0;
this.delegate.open(arg0);
}
public void close() throws ItemStreamException {
this.delegate.close();
}
#Override
public void write(List<? extends Object> items) throws Exception {
log.info("CommItemWriter.write() : items.size() : " + items.size());
stylesheet = new File("./config/style.xsl");
stylesource = new StreamSource(stylesheet);
String fileName = fileUtil.getFileName();
try {
transformer = TransformerFactory.newInstance().newTransformer(stylesource);
} catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
log.error("Exception while writing",e);
}
for (Object object : items) {
log.info("CommItemWriter.write() : Object : " + object.getClass().getName());
log.info("CommItemWriter.write() : FileName : " + fileName);
Source source = new DOMSource((Document) object);
Result outputTarget = new StreamResult(
new File(fileName));
transformer.transform(source, outputTarget);
}
}
In chunkListener there is nothing much i am doing.
Below is the job listener.
#Override
public void beforeJob(JobExecution jobExecution) {
log.info("JK: CommJobListener.beforeJob()");
}
#Override
public void afterJob(JobExecution jobExecution) {
log.info("JK: CommJobListener.afterJob()");
JobParameters jobParams = jobExecution.getJobParameters();
File inputFile = new File(jobParams.getString("inputFilePath"));
File outputFile = new File(jobParams.getString("outputFilePath"));
try {
if (jobExecution.getStatus().isUnsuccessful()) {
Files.move(inputFile.toPath(), Paths.get(inputErrorDir, inputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
Files.move(outputFile.toPath(), Paths.get(outputErrorDir, outputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
} else {
String inputFileName = inputFile.getName();
Files.move(inputFile.toPath(), Paths.get(inputCompletedDir, inputFileName),
StandardCopyOption.REPLACE_EXISTING);
Files.move(outputFile.toPath(), Paths.get(outputCompletedDir, outputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ioe) {
log.error("IOException occured ",ioe);
}
}
I am also using integration flow.
#Bean
public IntegrationFlow messagesFlow(JobLauncher jobLauncher) {
try {
Map<String, Object> headers = new HashMap<>();
headers.put("jobName", "commExportJob");
return IntegrationFlows
.from(Files.inboundAdapter(new File(env.getProperty(Const.INPUT_LANDING_DIR)))
,
e -> e.poller(Pollers
.fixedDelay(env.getProperty(Const.INPUT_POLLER_DELAY, Integer.class).intValue())
.maxMessagesPerPoll(
env.getProperty(Const.INPUT_MAX_MESSAGES_PER_POLL, Integer.class).intValue())
.taskExecutor(getFileProcessExecutor())))
.handle("moveFile","moveFile")
.enrichHeaders(headers)
.transform(jobTransformer)
.handle(jobLaunchingGw(jobLauncher))
.channel("nullChannel").get();
} catch (Exception e) {
log.error("Exception in Integration flow",e);
}
return null;
}
#Autowired
private Environment env;
#Bean
public MessageHandler jobLaunchingGw(JobLauncher jobLauncher) {
return new JobLaunchingGateway(jobLauncher);
}
#MessagingGateway
public interface IMoveFile {
#Gateway(requestChannel = "moveFileChannel")
Message<File> moveFile(Message<File> inputFileMessage);
}
#Bean(name = "fileProcessExecutor")
public Executor getFileProcessExecutor() {
ThreadPoolTaskExecutor fileProcessExecutor = new ThreadPoolTaskExecutor();
fileProcessExecutor.setCorePoolSize(env.getRequiredProperty(Const.INPUT_EXECUTOR_POOLSIZE, Integer.class));
fileProcessExecutor.setMaxPoolSize(env.getRequiredProperty(Const.INPUT_EXECUTOR_MAXPOOLSIZE, Integer.class));
fileProcessExecutor.setQueueCapacity(env.getRequiredProperty(Const.INPUT_EXECUTOR_QUEUECAPACITY, Integer.class));
fileProcessExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
fileProcessExecutor.initialize();
return fileProcessExecutor;
}
Try to return document itself instead of Object in read method of CommReader.java and then check whether its coming null or not in the writer to stop it.

How to combine Retrofit 2 with Realm and RxJava

I want to save retrofit responses to realm on the background thread then pass it to the UI Thread, but its a bit tricky since Realm is very touchy with threads. so the code would look like something like this, please submit your edits to all better solutions :)
restApi.userRealmList()
.doOnNext(userRealmModels -> {
if (userRealmModels != null){
mRealm = Realm.getInstance(mContext);
mRealm.asObservable()
.map(realm -> mRealm.copyToRealmOrUpdate(userEntity))
.subscribe(new Subscriber<Object>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
e.printStackTrace();
}
#Override
public void onNext(Object o) {
Log.d("RealmManager", "user added!");
}
});
}})
.map(userEntityDataMapper::transformAll)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<User>>() {
#Override
public void onCompleted() {
hideViewLoading();
}
#Override
public void onError(Throwable e) {
hideViewLoading();
showErrorMessage(new DefaultErrorBundle((Exception) e));
showViewRetry();
}
#Override
public void onNext(List<User> users) {
showUsersCollectionInView(users);
}
});
You code doesn't look like it can compile? E.g. what is userEntity. Also your copyToRealmOrUpdate isn't inside an transaction, so that will also crash, but it has nothing to do with threads.
If you want to save some data as a side-effect before sending it to the UI, you should be able to do the following:
restApi.userRealmList()
.doOnNext(userRealmModels -> {
if (userRealmModels != null) {
Realm realm = Realm.getInstance(mContext);
realm.beginTransaction();
realm.copyToRealmOrUpdate(userRealmModels);
realm.commitTransaction();
realm.close();
}})
.map(userEntityDataMapper::transformAll)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<User>>() {
#Override
public void onCompleted() {
hideViewLoading();
}
#Override
public void onError(Throwable e) {
hideViewLoading();
showErrorMessage(new DefaultErrorBundle((Exception) e));
showViewRetry();
}
#Override
public void onNext(List<User> users) {
showUsersCollectionInView(users);
}
});

InstantiationException while getLocation on Nokia device

New to Nokia development. I am trying to write a hello world for get GPS coordinates of my current location. What am I doing wrong here ?
public class HomeScreen extends MIDlet {
public HomeScreen() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Displayable current = Display.getDisplay(this).getCurrent() ;
if (current == null) {
UpdateJourney updateJourney = new UpdateJourney(this) ;
Display.getDisplay(this).setCurrent(updateJourney) ;
}
}
}
public class UpdateJourney extends Form implements CommandListener, Runnable {
private LocationProvider myLocation;
private Criteria myCriteria;
private Location myCurrentLocation;
private HomeScreen helloScreen;
private Command exitCommand;
private Thread getLocationThread = new Thread(this);;
public UpdateJourney(HomeScreen helloScreen) {
super("Taxeeta");
StringItem helloText = new StringItem("", "Taxeeta");
super.append(helloText);
this.helloScreen = helloScreen;
getLocationThread.start();
}
public double getMyLatitude() {
return myCurrentLocation.getQualifiedCoordinates().getLatitude();
}
public double getMyLongitude() {
return myCurrentLocation.getQualifiedCoordinates().getLongitude();
}
public void commandAction(Command command, Displayable arg1) {
if (command == exitCommand) {
helloScreen.notifyDestroyed();
}
}
public void run() {
myCriteria = new Criteria();
myCriteria.setHorizontalAccuracy(500);
try {
myLocation = LocationProvider.getInstance(myCriteria);
myCurrentLocation = myLocation.getLocation(60);
} catch (LocationException e) {
e.printStackTrace();
System.out
.println("Error : Unable to initialize location provider");
return;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error: Waited enough for location to return");
return;
}
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
exitCommand = new Command("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude(),
Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
}
}
In the application descriptor I had UpdateJourney as the MIDlet, I changed it to HomeScreen and it worked.

Resources