Async Error FIx Needed with GeoCoder - java

Don't understand how to fix this error in my code, "Method getText must be called from the UI thread, currently inferred thread is worker more... (⌘F1)".
In this line, String name = addressEdit.getText().toString(); the portion "addressEdit.getText()" is underlined.
I've looked and found similar but the solutions are directly applicable.
CODE BELOW -
private class GeocodeAsyncTask extends AsyncTask {
String errorMessage = "";
#Override
protected void onPreExecute() {
}
#Override
protected Address doInBackground(Void... none) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = null;
if (fetchType == USE_ADDRESS_NAME) {
String name = addressEdit.getText().toString();
try {
addresses = geocoder.getFromLocationName(name, 1);
} catch (IOException e) {
errorMessage = "Service not available";
Log.e(TAG, errorMessage, e);
}
} else {
errorMessage = "Unknown Type";
Log.e(TAG, errorMessage);
}
if (addresses != null && addresses.size() > 0)
return addresses.get(0);
return null;
}
Thanks in advance for your help!

Related

How do I save the id from chatid with the telegram api

Hello. I'm trying to solve this problem for a while now. For some
reason I keep getting null pointer exception when I try to save a
object in my repository. Below you can see what happens and my
functions.
java.lang.NullPointerException at com.br.einstein.api.service.ApiTelegram.sendMsg(ApiTelegram.java:104)
at
com.br.einstein.api.service.ApiTelegram.onUpdateReceived(ApiTelegram.java:81)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at
org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:317)
public void onUpdateReceived(Update update) {
ApiEinstein api = new ApiEinstein();
try {
JsonObject objSession = api.getSessionDetails();
String message = update.getMessage().getText();
api.sendChatRequest(objSession);
List < String > list = new ApiEinstein().ReadChatDetails(objSession);
sendMsg(update.getMessage().getChatId().toString(), list.toString());
new ApiEinstein().SendChatMessage(objSession, message);
api.syncChatSession(objSession);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void sendMsg(String chatId, String s) {
SendMessage sendMessage = new SendMessage();
// sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId);
sendMessage.setText(s);
long id = Long.valueOf(chatId);
Telegram telegram = new Telegram();
telegram.setChatId(id);
repository.save(telegram);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} ```

AsyncTask Not Running

I have an AsyncTask that downloads a bunch of images, as seen below:
class DownloadHelper extends AsyncTask<Void, Void, Void> {
public Context mContext;
private DBHelper mDatabase;
DownloadHelper(Context context) {
this.mContext = context;
mDatabase = new DBHelper(mContext);
}
#Override
protected Void doInBackground(Void... voids) {
List<Exercise> mExercises = mDatabase.getExercises();
for (int i = 0; i < mExercises.size(); i++) {
Exercise e = mExercises.get(i);
Log.d("path", e.getImage_start());
saveFile(e.getLink_start(), e.getImage_start());
saveFile(e.getLink_end(), e.getImage_end());
}
return null;
}
private void saveFile(String url, String path){
//region Save Bitmap To File
URL mURL = null;
try { mURL = new URL( url ); }
catch (MalformedURLException e) { Log.d("Error", "ce url de cacat smr yo niki nu merge"); e.printStackTrace();}
HttpURLConnection mConn = null;
try { mConn = (HttpURLConnection) mURL.openConnection(); mConn.setDoInput(true); mConn.connect(); }
catch (IOException e) {e.printStackTrace();}
Bitmap mBitmap = null;
try {
InputStream mInput = mConn.getInputStream();
mBitmap = BitmapFactory.decodeStream(mInput);
} catch (Exception e) { e.printStackTrace(); }
//endregion
//region Save Bitmap
if (mBitmap != null){
try {
FileOutputStream mOutput = new FileOutputStream(path);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mOutput);
mOutput.close();
} catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); }
}
}
}
and it is called in a function like this:
public void initialize(){
PermissionManager mManager = new PermissionManager() {};
mManager.checkAndRequestPermissions((Activity) mContext);
downloadExercises();
//region Create Exercises Folder To Store Images
File mFolder = mContext.getDir("exercises", Context.MODE_PRIVATE);
if (!mFolder.exists()) mFolder.mkdir();
Log.d("path", mFolder.getAbsolutePath());
//endregion
DownloadHelper mDownload = new DownloadHelper(mContext);
mDownload.execute();
}
However, when i debug the app, i have a breakpoint on mDownload.execute() and then some other ones in the doInBackground(), but the app never gets to the async task.
What am i doing wrong?
I had a similar issue, I believe you need to pass in null parameters when executing your async task:
mDownload.execute((Void) null);
If this doesn't help, perhaps your if statement is not passing, therefore your method is never run?
Just try this,
class DownloadHelper extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String response=null;
//** Do Your code here and must the result declare to response **//
return response;
}
}
In your main class after declare Asyntask then get the return value
DownloadHelper mDownload = new DownloadHelper();
mDownload.execute(mContext);
then add this line
String get_return=mDownload.get();
I figured out what was the problem. The Async was running but it seems that the downloadExercises() function added the exercises to the database AFTER the async would call getExercises() in order to download the images and therefore it didnt do anything. The solution i found was to prompt the user with a dialog to download the images AFTER the download and insertion of exercises was completed.

JavaFX null pointer exception at label.setText() [duplicate]

This question already has an answer here:
javafx using objects from MainController or other Controllers in proper Controller class
(1 answer)
Closed 5 years ago.
sorry. I don't speak english well so please understand me
I'm making smartmirror for java but I have problem with setText() function.
after calling weather api and saving location name to variable, I start label.setText() but it has null pointer exception.
I heard about platform.run later() method and task , but they don't work.
please help me T.T
There are my source
package SmartMirror.main;
import java.io.IOException;
public class SpeechClass {
WeatherController weather = new WeatherController();
// Logger
private Logger logger = Logger.getLogger(getClass().getName());
// Variables
public String result;
// Threads
Thread speechThread;
Thread resourcesThread;
Thread openThread;
// LiveRecognizer
private LiveSpeechRecognizer recognizer;
protected String location;
public void Speech(){
// Loading Message
logger.log(Level.INFO, "Loading..\n");
// Configuration
Configuration configuration = new Configuration();
// Load model from the jar
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
// if you want to use LanguageModelPath disable the 3 lines after which
// are setting a custom grammar->
// configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin")
// Grammar
configuration.setGrammarPath("resource:/grammars");
configuration.setGrammarName("grammar");
configuration.setUseGrammar(true);
try {
recognizer = new LiveSpeechRecognizer(configuration);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
// Start recognition process pruning previously cached data.
recognizer.startRecognition(true);
// Start the Thread
startSpeechThread();
startResourcesThread();
}
/**
* Starting the main Thread of speech recognition
*/
protected void startSpeechThread() {
// alive?
if (speechThread != null && speechThread.isAlive())
return;
// initialise
speechThread = new Thread(() -> {
logger.log(Level.INFO, "You can start to speak...\n");
try {
while (true) {
/*
* This method will return when the end of speech is
* reached. Note that the end pointer will determine the end
* of speech.
*/
SpeechResult speechResult = recognizer.getResult();
if (speechResult != null) {
result = speechResult.getHypothesis();
System.out.println("You said: [" + result + "]\n");
if(result.equals("one")){
System.out.println("startOpenThread");
startWeatherThread();
openThread.sleep(3000);
Platform.runLater(new Runnable(){
#Override
public void run(){
weather.setLabel();
openweather();
}
});
}
// logger.log(Level.INFO, "You said: " + result + "\n")
} else
logger.log(Level.INFO, "I can't understand what you said.\n");
}
} catch (Exception ex) {
logger.log(Level.WARNING, null, ex);
}
logger.log(Level.INFO, "SpeechThread has exited...");
});
// Start
speechThread.start();
}
/**
* Starting a Thread that checks if the resources needed to the
* SpeechRecognition library are available
*/
protected void startResourcesThread() {
// alive?
if (resourcesThread != null && resourcesThread.isAlive())
return;
resourcesThread = new Thread(() -> {
try {
// Detect if the microphone is available
while (true) {
if (AudioSystem.isLineSupported(Port.Info.MICROPHONE)) {
// logger.log(Level.INFO, "Microphone is available.\n")
} else {
// logger.log(Level.INFO, "Microphone is not
// available.\n")
}
// Sleep some period
Thread.sleep(350);
}
} catch (InterruptedException ex) {
logger.log(Level.WARNING, null, ex);
resourcesThread.interrupt();
}
});
// Start
resourcesThread.start();
}
protected void startWeatherThread() {
try{
openThread = new Thread(() -> {
weather.Weather(); // 날씨를 변수에 저장
});
} catch (Exception e){
}
// Start
openThread.start();
}
public void openweather(){
Stage dialog = new Stage(StageStyle.TRANSPARENT);
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(null);
Parent parent = null;
try {
parent = FXMLLoader.load(WeatherController.class.getResource("weather_scene.fxml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scene scene = new Scene(parent);
dialog.setScene(scene);
dialog.setResizable(false);
dialog.show();
}
}
package SmartMirror.Weather;
import java.io.BufferedReader;
public class WeatherController {
#FXML private Label labelLocation;
public String locationResult="", weatherResult="", tempResult="";
//날씨 API
public void Weather() {
try{
//OpenAPI call하는 URL
String urlstr = "http://api.openweathermap.org/data/2.5/weather?"
+"q=Chuncheon"
+"&appid=f1bccf50c733316db790a00a2d5165c6&units=metric";
URL url = new URL(urlstr);
BufferedReader bf;
String line;
String result="";
//날씨 정보를 받아온다.
bf = new BufferedReader(new InputStreamReader(url.openStream()));
//버퍼에 있는 정보를 문자열로 변환.
while((line=bf.readLine())!=null){
result=result.concat(line);
//System.out.println(line);
}
//문자열을 JSON으로 파싱
JSONParser jsonParser = new JSONParser();
JSONObject jsonObj = (JSONObject) jsonParser.parse(result);
//날씨 출력
JSONArray weatherArray = (JSONArray) jsonObj.get("weather");
JSONObject weather = (JSONObject) weatherArray.get(0);
//온도출력
JSONObject mainArray = (JSONObject) jsonObj.get("main");
double ktemp = Double.parseDouble(mainArray.get("temp").toString());
locationResult = (String) jsonObj.get("name");
weatherResult = (String) weather.get("main");
tempResult = Double.toString(ktemp) + "℃";
System.out.println("startWeatherThread" + locationResult);
bf.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public void setLabel(){
Platform.runLater(new Runnable(){
#Override
public void run(){
System.out.println(locationResult);
labelLocation.setText(locationResult);
}
});
}
}
First of all, I'm not recommending on using public attributes, I suggest you to check Why use getters and setters? so change your 3 public field to a private ones and then make getters and setters to them.
About your problem, I haven't seen your fxml code for it, but make sure you gave your label an identity also known as fx:id so it wouldn't cause it to be null.
Also make sure that you gave reference to your WeatherController in fx:controller

Get time of NTP-Server from Android App

Dear android developers,
I'm trying to implement the sntpclient class in my application but it didn't work.
Class: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/net/SntpClient.java
in my code I have the following lines:
public void onClickBtn(View v)
{
SntpClient client = new SntpClient();
if (client.requestTime("pool.ntp.org", 10)) {
long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
Toast.makeText(this, "Offset: " + now, Toast.LENGTH_LONG).show();
}
}
I really don't know what the meaning of network timeout is in this case.
It would be great, when someone has any idea or tip for me.
Thanks in advance!
You should put it in AsyncTask like this :
class GetNTPAsynctask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
private SntpClient sntpClient = new SntpClient();
return sntpClient.requestTime("pool.ntp.org", 30000);
}
}
Timeout: network timeout in milliseconds. So i use 30000 mean 30 seconds.
You can use this Full sample:
class getCurrentNetworkTime extends AsyncTask<String, Void, Boolean> {
private Exception exception;
protected Boolean doInBackground(String... urls) {
NTPUDPClient timeClient = new NTPUDPClient();
timeClient.setDefaultTimeout(3000);
InetAddress inetAddress = null;
boolean is_locale_date = false;
try {
inetAddress = InetAddress.getByName(G.TIME_SERVER);
TimeInfo timeInfo = null;
timeInfo = timeClient.getTime(inetAddress);
long localTime = timeInfo.getReturnTime();
long serverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
if (new Date(localTime) != new Date(serverTime))
is_locale_date = true;
} catch (UnknownHostException e) {
e.printStackTrace();
Log.e("UnknownHostException: ", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException: ", e.getMessage());
}
return is_locale_date;
}
protected void onPostExecute(boolean local_date) {
if(!local_date) {
Log.e("Check ", "dates not equal" + local_date);
}
}
}
How to use:
new getCurrentNetworkTime().execute();
Check that your manifest has this one:
<uses-permission android:name="android.permission.INTERNET" />

when calling the geocoder constructor in a thread the connection crashes

I'm trying hardly to implement a geocoder in android in a Runnable class:
This is the way I did it:
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
List<Address> list = geocoder.getFromLocation(
(int)(coord.getLat()), (int)(coord.getLon()), 1);
if (list != null && list.size()>0 ){
Address address=list.get(0);
String result = address.getAddressLine(0) + ", " + address.getLocality();
}
My class,Runnable is actually a thread that connects to a remote server and receives data from there using a buffer.
And here is my problem:
The connection with the server is or was quite good until I put the line with the geocoder inside my code.
Now once I've added the Geocoder lines this side of my connection with the server crashes!!!
Now I know for sure that is because of the geocoder because only today I've added it to my app and until now my app worked very well and the connection was strong....
Here is my entire code and if someone could tell how could I implement Geocoder in a better way please do:
public class ClientThread_special implements Runnable {
int serverPort = 6500;
private String serverIpAddress = "10.0.2.2";
Coordinate coord;
ObjectInputStream is;
boolean stop = false;
DBAdapter db;
boolean t = false;
int id;
Context context;
PrintStream strReturnedAddress;
public ClientThread_special(DBAdapter db, Context context) {
this.db = db;
this.context = context;
}
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverIpAddress, serverPort);
is = new ObjectInputStream(socket.getInputStream());
try {
while (!stop) {
coord = (Coordinate) is.readObject();
System.out.println("Date de la clientul de monitorizare:"
+ coord.getLat());
List<Address> list = geocoder.getFromLocation(
(int)(coord.getLat()), (int)(coord.getLon()), 1);
if (list != null && list.size()>0 ){
Address address=list.get(0);
String result = address.getAddressLine(0) + ", " + address.getLocality();
}
System.out.println("adresa returnata folosind geocoder:"
+ strReturnedAddress);
....................................................
}
} catch (Exception e) {
e.printStackTrace();
}
is.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
this.stop = true;
}
}
From the server I'm reading some object.... If is neccesary other further details I'm here
Try to put a Log.v("EXCEPTION","message",e); inside your IO try/catch block as mostly when geocoder fails throws an IOException. and that may help you as you'll know what exactly is going wrong. WHAT I FEEL is that geocoder sometime fails to return the address that corresponds to lat/long so check your lat/long and check for the list to NOT NULL then proceed in order to prevent the crash.like this ....if (list.size()>0) address=address_found ; else address="unknow address" ; and proceed like this,

Categories

Resources