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" />
Related
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.
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!
This question already has answers here:
Android AsyncTask don't return correct Result
(3 answers)
Closed 8 years ago.
in this below code i want to return value from AsyncTask with using an Interface. but i get wrong value and i can not return correct value from onPostExecute.
i'm developed this link tutorials with my code. i can not use correctly with that.
Interface:
public interface AsyncResponse {
void processFinish(String output);
}
Ksoap Main class:
public class WSDLHelper implements AsyncResponse{
public SoapObject request;
private String Mainresult;
public String call(SoapObject rq){
ProcessTask p =new ProcessTask(rq);
String tmp = String.valueOf(p.execute());
p.delegate = this;
return Mainresult;
}
#Override
public void processFinish(String output) {
this.Mainresult = output;
}
}
class ProcessTask extends AsyncTask<Void, Void, Void > {
public AsyncResponse delegate=null;
SoapObject req1;
private String result;
public ProcessTask(SoapObject rq) {
req1 = rq;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(this.req1);
AndroidHttpTransport transport = new AndroidHttpTransport(Strings.URL_TSMS);
transport.debug = true;
try {
transport.call(Strings.URL_TSMS + this.req1.getName(), envelope);
this.result = envelope.getResponse().toString();
} catch (IOException ex) {
Log.e("" , ex.getMessage());
} catch (XmlPullParserException ex) {
Log.e("" , ex.getMessage());
}
if (result.equals(String.valueOf(Integers.CODE_USER_PASS_FALSE))) {
try {
throw new TException(PublicErrorList.USERNAME_PASSWORD_ERROR);
} catch (TException e) {
e.printStackTrace();
}
}
Log.e("------------++++++++++++++++-----------", this.result);
return null;
}
protected void onPostExecute(String result) {
/* super.onPostExecute(result);*/
delegate.processFinish(this.result);
}
}
please help me to resolve this problem
That can't work. You are creating and executing the AsyncTask (asynchronously!) and then call return Mainresult (synchronously!) when it hasn't received the result yet. The solution is to remove the redundant class WSDLHelper and access ProcessTask directly
Beside that, you're using AsyncTask incorrectly (saving the result in a class variable instead of passing it as a parameter). Here's the full version:
public class ProcessTask extends AsyncTask<Void, Void, String> {
public AsyncResponse delegate=null;
SoapObject req1;
public ProcessTask(SoapObject rq, AsyncResponse delegate) {
req1 = rq;
this.delegate = delegate;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(this.req1);
AndroidHttpTransport transport = new AndroidHttpTransport(Strings.URL_TSMS);
transport.debug = true;
String result = null;
try {
transport.call(Strings.URL_TSMS + this.req1.getName(), envelope);
result = envelope.getResponse().toString();
} catch (IOException ex) {
Log.e("" , ex.getMessage());
} catch (XmlPullParserException ex) {
Log.e("" , ex.getMessage());
}
if (result != null && result.equals(String.valueOf(Integers.CODE_USER_PASS_FALSE))) {
try {
throw new TException(PublicErrorList.USERNAME_PASSWORD_ERROR);
} catch (TException e) {
e.printStackTrace();
}
}
Log.e("------------++++++++++++++++-----------", result);
return result;
}
protected void onPostExecute(String result) {
/* super.onPostExecute(result);*/
delegate.processFinish(result);
}
}
Now you would execute ProcessTask from outside like this, which will make sure you receive the result asynchronously:
new ProcessTask(rq, new AsyncResponse() {
#Override
public void processFinish(String output) {
// do whatever you want with the result
}
}).execute();
Your result will always be null, because you return null in the doInBackground() method. The value you return in doInBackground() will be passed to onPostExecute(). Change your AsyncTask<Void, Void, Void> to AsyncTask<Void, Void, String>, and return the result. This will call onPostExecute(String result) with the correct result.
Perhaps this link might help you a bit: http://bon-app-etit.blogspot.be/2012/12/using-asynctask.html
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am having some major problems with my new project. I have a client app on my PC that is sending a simple String of data to the phone over the WiFi LAN connection. When recieved it should be split to its component parts and then an SMS sent.
I'll be honest, this is my first Android project but I'm determined to get this working.
When I send the command from my client, the app is failing and being caught in the catch labeled with Log.w("ServerRunnable", "Exception 2"); below. Id really appreciate some advice on this? I don't know why it won't work!
public class ListeningService extends Service {
private int iNotificationIcon = 1;
Handler hHandler;
Thread thServerThread = null;
private ServerSocket oServerSocket = null;
private static final String _S_DELIMITER = "##t2tDELIMITER##";
private static final int _I_SERVER_PORT = 50001;
#Override
public IBinder onBind(Intent arg0) {
Toast.makeText(this, "Service Bound", Toast.LENGTH_LONG).show();
return null;
}
#Override
public int onStartCommand(Intent oIntent, int iFlags, int iStartID) {
addNotification(getString(R.string.app_name), "Server listening on xxx.xxx.xxx.xxx:ppppp", iNotificationIcon, true);
/* Server Threading */
/*hHandler = new Handler() {
#Override
public void handleMessage(Message mMsg) {
// TODO Auto-generated method stub
showMessageBox(mMsg.getData().toString(), "Data Bundle", true);
super.handleMessage(mMsg);
}
};*/
this.thServerThread = new Thread(new ServerRunnable());
//showToast("Thread Created but not started yet", false);
this.thServerThread.start();
return START_STICKY;
}
public class ServerRunnable implements Runnable {
public ServerRunnable() {
/**/
}
public void run() {
Socket oSocket;
try {
oServerSocket = new ServerSocket(_I_SERVER_PORT);
Log.w("ServerRunnable", "oServerSocket created");
} catch (Exception e) {
e.printStackTrace();
Log.w("ServerRunnable", "Exception 1");
}
while (!Thread.currentThread().isInterrupted()) {
try {
oSocket = oServerSocket.accept();
CommsThread commThread = new CommsThread(oSocket);
new Thread(commThread).start();
Log.w("ServerRunnable", "oSocket created");
} catch (Exception e) {
e.printStackTrace();
Log.w("ServerRunnable", "Exception 2");
}
}
}
}
public class CommsThread implements Runnable {
private Socket oClientSocket;
private BufferedReader brInput;
public CommsThread(Socket oSocket) {
this.oClientSocket = oSocket;
try {
this.brInput = new BufferedReader(new InputStreamReader(this.oClientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String sRead = brInput.readLine();
//hHandler.post(new SendSMSThread(sRead));
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class SendSMSThread implements Runnable {
String sPhoneNumber = "";
String sTextMessage = "";
int iMessageLength = 0;
public SendSMSThread(String sRead) {
/* Received */
//showMessageBox(sRead, "Raw Data", true);
int iDelimiterStart = sRead.indexOf(_S_DELIMITER);
int iDelimiterLen = _S_DELIMITER.length();
/* Split the input */
sPhoneNumber = sRead.substring(0, (iDelimiterStart+1));
sTextMessage = sRead.substring((iDelimiterStart + iDelimiterLen));
//showMessageBox(sTextMessage, sPhoneNumber, true);
}
public void run() {
if ((sPhoneNumber.length() == 11) && (sTextMessage.length() > 0)) {
sendSMS(sPhoneNumber, sTextMessage, true);
}
}
}
StackTrace:
01-23 23:48:42.673: W/ServerRunnable(15567): Exception 2
01-23 23:48:42.673: W/StackTrace(15567): java.lang.NullPointerException
01-23 23:48:42.673: W/StackTrace(15567): at uk.co.tip2tail.wintextserver.ListeningService$ServerRunnable.run(ListeningService.java:78)
01-23 23:48:42.673: W/StackTrace(15567): at java.lang.Thread.run(Thread.java)
This only seems to be occuring after I have stopped and restarted the service. The initial running of the service seems to be ok, although it still does nothing when the data is recieved! Im totally lost. Every book ive read has code like i do but this just wont work!
Any help appreciated.
I had over complicated things.
I have since went back and completely changed the code for the Service, only running 2 Threads.
And it now works!
Thank you for the constructive comments above. :)
I am trying to get data from RSS feed to display it in fragments (11 fragment), but each time i pass to a new fragment the UI block for a several seconds because it's fetching data so i try to use asyncTask to do this in background but it seems that it does not work.
public class AndroidSaxFeedParser extends AsyncTask<String, Long, ArrayList<Article>>{
String dt;
String bb;
String nameCat;
RootElement root;
Element item;
static final String RSS = "rss";
static final String FEED = "feed";
static final String ENTRY = "entry";
static final String CHANNEL = "channel";
static final String PUB_DATE = "pubDate";
static final String DESCRIPTION = "description";
static final String LINK = "link";
static final String TITLE = "title";
static final String ITEM = "item";
static final String CATEGORY = "category";
static final String DURATION = "itunes:duration";
ArrayList<Article> rssItems = new ArrayList<Article>();
public URL feedUrl;
Context mContext;
public AndroidSaxFeedParser(Context context)
{
mContext = context;
}
// ProgressDialog pd = new ProgressDialog(mContext);
#Override
protected void onPostExecute(ArrayList<Article> result) {
// pd.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// ProgressDialog.show(mContext, "", "Chargement...");
super.onPreExecute();
}
#Override
protected ArrayList<Article> doInBackground(String... params) {
try {
feedUrl = new URL(params[0]);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
final Article currentRssItem = new Article();
root = new RootElement(RSS);
Element channel = root.getChild(CHANNEL);
item = channel.getChild(ITEM);
item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentRssItem.setTitle(body);
Log.i("Title Article", " "+currentRssItem.getTitle());
}
});
item.getChild(CATEGORY).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentRssItem.setCategorie(body);
Log.i("Category Article", " "+currentRssItem.getCategorie());
}
});
item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
String imgUrl, desc;
try {imgUrl = body.substring(body.indexOf("src=")+5,body.indexOf("\"", body.indexOf("src=")+6));}
catch (Exception e)
{imgUrl = "";}
try {desc=body;}
catch (Exception e)
{ desc = "";}
currentRssItem.setImageUrl(imgUrl);
currentRssItem.setDescription(desc);
Log.i("Image URL Article", " "+currentRssItem.getImageUrl());
Log.i("Description Article", " "+currentRssItem.getDescription());
}
});
item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentRssItem.setPubDate(body);
Log.i("Date Article", " "+currentRssItem.getPubDate());
}
});
item.setEndElementListener(new EndElementListener(){
public void end() {
rssItems.add(currentRssItem.copy());
}
});
try {
Xml.parse(feedUrl.openConnection().getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return rssItems;
}
I am calling it this way in each fragment
ArrayList<Article> feeds ;
try {
feeds=AndroidSaxFeedParser.execute(url).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
You should always download the file and save it as a String before asking the XML class to parse it.
public String getXml(String url) {
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
// HTTP OK 200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
// NOTE: Here need to set the default charset to be UTF-8
content = EntityUtils.toString(entity, "UTF-8");
return content;
}
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
content = null;
}
}
In this way it is less likely to get interrupted due to connection problem. In addtition, please tell us more about what "it seems that it does not work" means. Did it fail to parse the xml, fail to run the task, or fail what?
Also, you should not be calling
feeds=AndroidSaxFeedParser.execute(url).get();
in your fragment. You should modify this function of your AndroidSaxFeedParser:
#Override
protected void onPostExecute(ArrayList<Article> result) {
feeds = result;
// Do whatever you wanna do to set up things with the feeds
}
To make this work you must put your AndroidSaxFeedParser as an inner class of your fragment.