automated email sending failure - java

I am using this article to help me send automated emails, but I am having an issue in which nothing seems to be happening and no errors are generated.
I used AsyncTask but it is not sending the mail at all.
public class Sender extends AsyncTask< Void, Void, Void> {
private Exception exception;
protected Void doInBackground(String... arg0) {
Log.v("aws", "OPEN asa");
Mail m = new Mail("email#email.com", "password");
String[] toArr = {"to#mail.com"};
m.setTo(toArr);
m.setFrom("from#gmail.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an >Android device.");
m.setBody("Email body.");
try {
//m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Log.v("aws", "OK SENT");
} else {
Log.v("aws", "NOT SENT");
}
} catch(Exception e) {
Log.v("aws", "EXCEPTION . NOT SENT");
}
return null;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(Void... arg0) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
I have used new Sender().execute(); to execute the task, but nothing is happening and no errors are being thrown.
What am I doing wrong?
EDIT
Code has two doInBackground such that second overridden my working doInBackground

Be careful, you have two doInBackground() methods in your code, and the #Override version is what gets executed by the AsyncTask. Just move the code from the wrong doInBackground() version to the right one and delete the wrong one.

Related

How does AsyncTask work one process to another one?

I'm currently studying android on my own and pretty new to java. I'm wondering how AsyncTask works like this: onPreExecute() -> doInBackground() -> onPostExecute(). When I look at others define their AsynTask, it seems like only method is declared in their code with no calls upon the method. I can't figure out how doInBackground() comes after onPreExecute() with no code that links both like:
onPreExecute(){ ~~~~~ call doInBackground()}
My point is that when AsyncTask.execute() is called, onPreExecute() is called, then doInBackground(), finally onPostExecute(). I couldn't find any code in library that actually connects these together. All I could find is this:
#MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
#MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
Here when AsyncTask.execute() is called, onPreExecute() is called. But without any connection to doInBackground the task works just fine. I feel like I'm missing some fundamental logic or process of java or android. Plz, help me with this unsolved question in mind. Sample code is shown below. Thank you in advance.
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected String[] doInBackground(String... params) {
/* If there's no zip code, there's nothing to look up. */
if (params.length == 0) {
return null;
}
String location = params[0];
URL weatherRequestUrl = NetworkUtils.buildUrl(location);
try {
String jsonWeatherResponse = NetworkUtils
.getResponseFromHttpUrl(weatherRequestUrl);
String[] simpleJsonWeatherData = OpenWeatherJsonUtils
.getSimpleWeatherStringsFromJson(MainActivity.this, jsonWeatherResponse);
return simpleJsonWeatherData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String[] weatherData) {
// COMPLETED (19) As soon as the data is finished loading, hide the loading indicator
mLoadingIndicator.setVisibility(View.INVISIBLE);
if (weatherData != null) {
// COMPLETED (11) If the weather data was not null, make sure the data view is visible
showWeatherDataView();
/*
* Iterate through the array and append the Strings to the TextView. The reason why we add
* the "\n\n\n" after the String is to give visual separation between each String in the
* TextView. Later, we'll learn about a better way to display lists of data.
*/
for (String weatherString : weatherData) {
mWeatherTextView.append((weatherString) + "\n\n\n");
}
} else {
// COMPLETED (10) If the weather data was null, show the error message
showErrorMessage();
}
I guess you shouldn't waste time on AsyncTask since it is deprecated.
Instead you should focus on coroutines, recommended by google here , or some other state of the art framework to achive what you want (e.g. rx java)
Yes, you are correct. The logic is onPreExecute() -> doInBackground() -> onPostExecute()
Synchronous VS asynchronous
You can read this article for a better understanding even though it's using Javascript to explain it.

How to run process inside loop after previous process is finished? Java

Long story short, i want to upload multiple images to my server using Retrofit 2. i want to loop the process of sending single image based on the size of List image but asynchronously, so second upload only run if the first upload is succeeded. Some people tell me i should send an Array of File to my server instead and parse the array there, but i want to know if there is an error while uploading in client side or not. that way if there is an error (network problem) on first loop, second loop will stop running.
I really don't have clear idea as for how to do the task above, but here is a start.
public class UploadAllImages extends AsyncTask<Void, Void ,Void>{
#Override
protected Void doInBackground(Void... params) {
doSingleUpload(image);
return;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(upload == succeeded){
new UploadAllImage().execute();
}
}
}
I would probably solve it like this:
public class UploadImages extends AsyncTask<Image, Integer, Boolean> {
#Override
protected Boolean doInBackground(Image... images) {
List<Image> remainingImages = new ArrayList<>(Arrays.asList(images));
while (!remainingImages.isEmpty()) {
boolean success = doSingleUpload(remainingImages.remove(0));
if (!success) {
return false;
}
}
return true;
}
#Override
protected void onPostExecute(Boolean success) {
// Handle the result of all uploads
}
}

Using android login template correctly

I am new to android and java and am trying to setup a login page that posts to a webpage that verifies the credentials and returns a cookie.
I am using the login template included with eclipse. I am not sure what to put for the
// TODO: attempt authentication against a network service.
All I need it so post to my page like this: www.mywebsite.com/login?userid=john&password=test
and if the credentials are correct I get a json success string and cookie back. How can I incorporate this into this template or what do i need to put in place of the authentication against a network service
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
edit: I tried searching for an example of this but did not find one that fit my case. Any links to a solution or example of what im trying to do are appreciated.

Unable to call methods from onPostExecute

I am using the an asynchronous task to run a JSON downloader as thus: (abridged)
public class JSONDownloader extends AsyncTask<Object, Object, Object>{
#Override
protected Object doInBackground(Object... params) {
if(JSONstate == false){
try {
final URL url = new URL([REDACTED]);
final URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConnection.connect();
final InputStream inputStream = urlConnection.getInputStream();
final StringBuilder sb = new StringBuilder();
while (inputStream.available() > 0) {
sb.append((char) inputStream.read());
}
String result = sb.toString();
JSONObject jsonOrg = new JSONObject(result);
String ok = "ok";
Response = jsonOrg.getString("response");
System.out.println(Response);
if(Response.equals(ok)){
Settingsresponse = true;
orgName = jsonOrg.getString("orgName");
System.out.println("orgName" + orgName);
accessPointName = jsonOrg.getString("attendanceRecorderName");
System.out.println("accessPointName" + accessPointName);
lat = jsonOrg.getString("latitude");
System.out.println("lat" + lat);
longi = jsonOrg.getString("longitude");
System.out.println("longi" + longi);
floor = jsonOrg.getString("floor");
System.out.println("floor" + floor);
orgId = jsonOrg.getString("orgId");
System.out.println("orgId" + orgId);
}
else{
System.out.println("Data sent was erroneous");
Settingsresponse = false;
}
} catch (Exception e) {
System.err.print(e);
}
}
else if(JSONstate == true){
try {
[redacted]
}
else{
System.out.println("Data sent was erroneous");
Settingsresponse = false;
}
} catch (Exception e) {
System.err.print(e);
}
}
return null;
}
protected void onPostExecute(Void result){
if(JSONstate == false){
System.out.println("This piece of code is definitely being run");
setfields();
}
else if(JSONstate == true){
settestfields();
//This method does not run upon the completion of the JSON request, as it supposedly should
}
}
}
Once the JSONRequest has been completed, the 'onPostExecute' method doesn't run. I have been attempting to use this method so that a set of fields can be updated as soon as the request is complete, instead of having to set a definite wait time. Am I simply utilizing the code wrong? Or is there something I've missed?
You aren't overriding the correct method for onPostExecute.
You have:
protected void onPostExecute(Void result)
You need:
protected void onPostExecute(Object result)
Notice the third generic parameter you supplied was of type Object. That's the type that onPostExecute uses as an argument. So, the method signature for onPostExecute needs to accept an Object, not Void.
You should probably use a result type of boolean here rather than object, and remove the Json state class variable. This keeps your AsyncTask more flexible, and could allow you to display some indication the operation completed to the user after execution.
I have to say you codes in AsyncTask is nothing matches the point.
AsyncTask is designed as another thread running out from the UI-thread. So you should either use it as a inner class which is in a running UI-thread, then the onPostExecute() part can do something to show the result, or you as your codes, if you leave it as a stand alone class. You should design an interface, other class, like activity or fragment, which run new AsyncTask.execute() should implements that interface.
Also, java is not javascript. Your variables in doInBackground() is only limited in the function. So what you did in onPostExecute() will get nothing.
You should either use
JSONObject jsonOrg
as a class variable or you should return that at the end of doInBackground() and gain it back in onPostExecute()
After all, I suggest you look at the api document's example. Although it is a little complex, but it shows everything perfect.
try to use override methods
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.i("in on ", "entered");
hideProgress();
}
As suggested by william the type should match with the override methods. I have edited the answer below
public class JSONDownloader extends AsyncTask<Object, Object, Object>
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
}

android.os.NetworkOnMainThreadException android call webservice [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
whoaa
i really need help, why my code result like that?
this is my code :
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
try{
HttpResponse response = httpClient.execute(httpPost);
String jsonResult = convertStreamToString((response.getEntity().getContent())).toString();
JSONObject obj = (JSONObject) new JSONTokener(jsonResult).nextValue();
JSONObject obj2 = obj.getJSONObject("GetRingkasObjekPajak_SingleResult");
String nameWP = obj2.getString("NM_WP");
TextView tv = (TextView)findViewById(R.id.dummy_text_three);
tv.setText(jsonResult);
}catch (MalformedURLException e) {
// URL is invalid
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("url invalid");
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("RTO");
} catch (IOException e) {
// could not read response body
// (could not create input stream)
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("couldnt read response");
} catch (JSONException e) {
// response body is no valid JSON string
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("json response fail");
}catch (Exception e) {
// TODO: handle exception
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText(e.toString());
}
i also have added internet permission
please help me
how to improve my code, so this problem solved.
Here is an example of Async task... Hope it will be helpfull to you.
private class YourAsyncTaskClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//your http network call here.
return null;
}
#Override
protected void onPostExecute(String result) {
//update your ui here
}
#Override
protected void onPreExecute() {
//do any code before exec
}
#Override
protected void onProgressUpdate(Void... values) {
//If you want to update a progress bar ..do it here
}
}
Finally call this class from anywhere you want like..
new YourAsyncTaskClass().execute();
you can not perform network operations from main UI thread. you need to do networking related tasks in different thread. Better use AsyncTask
According to the doc
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it's heavily
discouraged.
NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.
There is an article about Painless Threading on the Android developer site which is a good introduction to this, and will provide you with much better depth of answer than can be realistically provided here.
Run your code in AsyncTask.
You can learn about asyncTask here is best explanation with good example .
call your webservice inside aynctask.
private class NetworkTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// call your network operation here
}
}

Categories

Resources