Async running twice - android

I got an async task that posts JSON data, the web service i post it to sends it as an email. I have a problem now the email is being sent twice. I already disabled the button and added the progress dialog while the task is on doInBackground. I cant seem find the error why it sends twice. In my logs it only returns the success once.
Here is the code of the async task
public class postEmail extends AsyncTask<String, String, String>{
String response;
#Override
protected void onPostExecute(String s) {
pd.dismiss();
if (response.contains("success")) {
Toast.makeText(getActivity(), "Message successfully sent", Toast.LENGTH_LONG).show();
Log.d("success", "sent success");
clearEditText();
editSubject.requestFocus();
}
else {
Toast.makeText(getActivity(), "Sending Failed. Kindly check your internet connection", Toast.LENGTH_LONG).show();
}
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(getActivity(), R.style.MyTheme);
pd.setCancelable(false);
pd.setMessage("Sending...");
pd.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pd.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
jsonParser = new JSONParser();
Log.d("POST EMAIL", "SENDING");
String finalEmail = "qcqpsd.admin#stluke.com.ph";
String finalCcEmail = "nolascolee#gmail.com";
String postUrl = "http://qpsdev.stluke.com.ph/webservice/qpsSendEmail";
List<NameValuePair> post_email = new ArrayList<NameValuePair>();
post_email.add(new BasicNameValuePair("email", finalEmail));
post_email.add(new BasicNameValuePair("subject", finalSubject));
post_email.add(new BasicNameValuePair("message", finalMessage));
post_email.add(new BasicNameValuePair("sender", finalSender));
post_email.add(new BasicNameValuePair("cc", finalCcEmail));
response = jsonParser.getJSONFromPostURL(postUrl, post_email);
Log.d("result", response);
return result = jsonParser.getJSONFromPostURL(postUrl, post_email);
}
}
And here is the code for the button:
btnSend.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getValue();
if(isConnected)
{
finalizeString();
new postEmail().execute();
}
else{
Toast.makeText(getActivity(), "Please check your connection",Toast.LENGTH_LONG).show();
}
}
});

response = jsonParser.getJSONFromPostURL(postUrl, post_email);
Log.d("result", response);
return result=jsonParser.getJSONFromPostURL(postUrl,post_email);
in here you send the file twice,change the return part and don't call method again mate

Related

Login in android using json post method

Im working on an android application with a login page using a json web service(POST). When I try to login it crashes.
Here is my code:
login = (Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = edit_email.getText().toString().trim();
String password = edit_password.getText().toString().trim();
call_api(email, password);
}
});
private void call_api(final String email, final String password) {
AsyncTask<String,String,String> sync=new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd.setMessage("Please wait");
pd.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient clent = new DefaultHttpClient();
HttpPost post = new HttpPost("http://steerapps.com/yardin/webservice.php?action=login?email="+email+"&password="+password);
try {
HttpResponse respon = clent.execute(post);
result1 = EntityUtils.toString(respon.getEntity());
JSONObject object = new JSONObject(result1);
String s = object.getJSONObject("response").getString("id");
message = object.getJSONObject("response").getString("message");
Log.e("message", "" + message);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.cancel();
if (message.equalsIgnoreCase("You are login Successfully"))
{
Intent it=new Intent(login_Activity.this,MainActivity.class);
startActivity(it);
Toast.makeText(getApplicationContext(),
"Login Successfully ", Toast.LENGTH_LONG)
.show();
}else {
Toast.makeText(getApplicationContext(),
"Login Failed ", Toast.LENGTH_LONG)
.show();
}
}
};
sync.execute();
}
Return message instead of null, you are returning null to onPostExecute method by your doInBackground() method which will be accepted by "String s" argument and you are calling super.onPostExecute(s) so , the null argument is passing to that method so, just change this line
return null
to
return message
in your doInBackground Method :)
Make String s global and then change
String s = object.getJSONObject("response").getString("id");
message = object.getJSONObject("response").getString("message");
to
s = object.getString("message");

How to make a Main Thread waiting for the AsyncTask android, without blocking the UI

I am trying to make login view.
I' d like to start a new AsyncTask that performs the REST call to the server and shows a progress bar. I need that the UI main thread wouldn't block and it must show a toast with message (like success or fail) depending on what the AsyncTask returns .
Here the code:
SetupActivity (main thread):
//Get reference SignUp Button
Button signupButton = (Button)myDialog.findViewById(R.id.button_signup_OK);
signupButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get all the textfield content from the form
name=((EditText)myDialog.findViewById(R.id.nameEditText)).getText();
surname=((EditText)myDialog.findViewById(R.id.surnameEditText)).getText();
email=((EditText)myDialog.findViewById(R.id.emailEditText)).getText();
password=((EditText)myDialog.findViewById(R.id.passwordEditText)).getText();
password_Retyped=((EditText)myDialog.findViewById(R.id.passwordRepEditText)).getText();
//Get hash from password
hashPassword=DigestMd5.md5(password);
hashPasswordRep=DigestMd5.md5(password_Retyped);
//Check if the fields are null
if(name.toString().equals("")){
((EditText) myDialog.findViewById(R.id.nameEditText)).setError(getString(R.string.mandatoryField));
}
if(surname.toString().equals("")){
((EditText) myDialog.findViewById(R.id.surnameEditText)).setError(getString(R.string.mandatoryField));
}
if(email.toString().equals("") ){
((EditText) myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.mandatoryField));
}else{
if(!new EmailValidator().validate(email.toString())){
((EditText)myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.emailWrong));
}
}
if(password.toString().equals("")){
((EditText) myDialog.findViewById(R.id.passwordEditText)).setError(getString(R.string.mandatoryField));
}
if(password_Retyped.toString().equals("")){
((EditText) myDialog.findViewById(R.id.passwordRepEditText)).setError(getString(R.string.mandatoryField));
}
//Check match password
if(!hashPassword.equals(hashPasswordRep)){
((EditText)myDialog.findViewById(R.id.passwordEditText)).setError(getString(R.string.passwordNotMatching));
((EditText)myDialog.findViewById(R.id.passwordRepEditText)).setError(getString(R.string.passwordNotMatching));
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
//Start AsyncTask
new loadingBar().execute().get();
Boolean resultOK = ackJSON.has("result");
if(resultOK){
//close dialog
myDialog.dismiss();
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_success,(ViewGroup) findViewById(R.id.custom_toast_layout_id));
Toast toastOK = new Toast(getApplicationContext());
toastOK.setDuration(Toast.LENGTH_LONG);
toastOK.setView(layout);
toastOK.show();
}else{
//Feedback both using Toasts and textedit
((EditText) myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.userAlreadyIn));
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_erroruser,(ViewGroup) findViewById(R.id.custom_toast_no_user));
Toast toastNoUser = new Toast(getApplicationContext());
toastNoUser.setDuration(Toast.LENGTH_SHORT);
toastNoUser.setGravity(Gravity.TOP,0,50);
toastNoUser.setView(layout);
toastNoUser.show();
}
} catch (IOException e) {
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_errorconnection,(ViewGroup) findViewById(R.id.custom_toast_no_noConn));
Toast toastNoConn = new Toast(getApplicationContext());
toastNoConn.setDuration(Toast.LENGTH_SHORT);
toastNoConn.setGravity(Gravity.TOP,0,50);
toastNoConn.setView(layout);
toastNoConn.show();
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
}
class loadingBar extends AsyncTask<Void,Integer,JSONObject>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setProgress(0);
progress.show();
}
#Override
protected JSONObject doInBackground(Void... arg0)
{
ackJSON = null;
try
{
for(int i=0;i<2;i++)
{
publishProgress(new Integer[]{i*10});
Thread.sleep(1200);
}
String ack=HTTPRest.putNewUser(name.toString(),surname.toString(),email.toString(),hashPassword);
ackJSON=new JSONObject(ack);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ackJSON;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progress.setProgress(values[0].intValue());
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progress.dismiss();
ackJSON=result;
}
}
Please let me know for any error in code
Thank you
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
//checkLogin(email, password);
new AttemptLogin().execute();
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
class AttemptLogin extends AsyncTask<String, String, String>{
/** * Before starting background thread Show Progress Dialog * */
boolean failure = false;
#Override protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(AppConfig.URL_LOGIN, "POST", params);
// checking log for json response
//devraj......................
Log.d("Login attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1){
session.setLogin(true);
Log.d("Successfully Login!", json.toString());
Intent intent = new Intent(LoginActivity.this,Secondpage.class);
startActivity(intent);
return json.getString(TAG_MESSAGE);
}
else{
return json.getString(TAG_MESSAGE);
}
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
/** * Once the background process is done we need to Dismiss the progress dialog asap * **/
protected void onPostExecute(String message)
{
pDialog.dismiss();
if (message != null){
Toast.makeText(First.this, message, Toast.LENGTH_LONG).show();
}
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
All is correct but you will change for this code
if(name.toString().isEmpty()){
}
because your code is some time problem when you not enter any value then not check your condition. Your code will check only black space.
You can show Toast in your onPostExecute() method
The lifecycle of Asynktask is runs like this
onPreExecute() -> runs first
doInBackground() -> After onPreExecute
and
`onPostExecute()` -> After doInBackground
So you can update UI or show Toast in onPostExecute()
You can do your work inside onPostExecute method of AsyncTask
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progress.dismiss();
ackJSON=result;
//do your work here show toast or move to next activity
}
progress.setCancelable(false);

How to confirm a log in Android?

I am trying to write a method that i can log into an online database. It works fine, but when i write wrong user/pwd i get a message explain me that i have to put the right user/pwd, and if i try one more time with wrong user/pwd i get "You are already logged in!". I don't know how to manage the inlogging?- i want the code tell me that i'm not logged in and try again?! -
Any help is very appreciate - Thanks, Steve.
There is the method (i use BroadcastReceiver to get the response from my AsyncTask-onPosExecute()) :
public void logIn() {
String user = edUser.getText().toString(), pwd = edPwd.getText().toString();
if (httpClient == null) {
httpClient = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("Passord", pwd));
new AsyncTaskLogIn(this).execute(new Pair<>(nameValuePairs, httpClient));
} else {
Toast.makeText(this, "You are already logged in!", Toast.LENGTH_LONG).show();
}
LocalBroadcastManager.getInstance(this).registerReceiver(LogIn,
new IntentFilter("log_in"));
}
private BroadcastReceiver LogIn = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String result = intent.getStringExtra("myLogIn");
tvMessage.setText(result);
}
};
1 - Replace the string "You are already logged in!" with "You aren't logged in!".
2 - After logging in, simply disable/hide the login Button.
3 - You could also set a global boolean variable logged to true when logged in.
In the Button's click handler, if logged, then show "You are already logged in!".
Else, do the login procedure, setting logged to true or false depending if the login credentials match or not, respectively.
The logic of your codes seems incorrect. Change to this:
if (httpClient == null) {
httpClient = new DefaultHttpClient();
}
List<NameValuePair> nameValuePairs = new ArrayList<>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("Passord", pwd));
new AsyncTaskLogIn(this).execute(new Pair<>(nameValuePairs, httpClient));
These codes ensure httpClient is not null
PS:If you want to tell whether you logged in successfully or not, you need to override the onPostExecute of your AsyncTaskLogin.
Try this:This is useful to you.
Login.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
System.out.println("is internet present:::"+isInternetPresent);
String username=usrname.getText().toString();
String password=paswd.getText().toString();
if(!username.equals("")&&!password.equals(""))
{
if(isInternetPresent)
{
System.out.println(username);
System.out.println(password);
usernamepassed=username;
System.out.println("inside attempt login");
new AttemptLogin().execute();
}
else
{
System.out.println("No network connection.");
}
}
else if(!password.equalsIgnoreCase(""))
{
System.out.println("Please enter username.");
}
else if(!username.equalsIgnoreCase(""))
{
System.out.println("Please enter password.");
}
else
{
System.out.println("Enter login credentials.");
}
}
});
Async task::
class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("username", usrname.getText().toString()));
params1.add(new BasicNameValuePair("password", paswd.getText().toString()));
JsonParser jLogin = new JsonParser();
System.out.println(usrname.getText().toString());
System.out.println( paswd.getText().toString());
JSONObject json = jLogin.makeHttpRequest(loginurl,"POST", params1);
System.out.println("value for json::"+json);
if(json!=null)
{
try
{
if(json != null)
{
System.out.println("json value::"+json);
JSONObject jUser = json.getJSONObject(TAG_SRESL);
successL = jUser.getString(TAG_SUCCESS1);
username1 = jUser.getString(TAG_USERNAME );
password1 = jUser.getString(TAG_PASSWORD);
orgid=jUser.getString(TAG_ORGID);
role=jUser.getString(TAG_ROLE);
enabled=jUser.getString(TAG_ENABLED);
System.out.println("username value:::"+username);
System.out.println("password value::"+password);
System.out.println("role value"+role);
Intent intentSignUP=new Intent(getApplicationContext(),DashboardActivity.class);
startActivity(intentSignUP);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
else{
successL ="No";
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String file_url) {
super.onPostExecute(file_url);
System.out.println("in post execute");
pDialog.dismiss();
if(JsonParser.jss.equals("empty"))
{
System.out.println("json null value");
System.out.println("Server not connected.");
pDialog.dismiss();
}
else if(successL.equalsIgnoreCase("No")){
System.out.println("Invalid username or password.");
pDialog.dismiss();
}
}
}

Toast message not displaying

In the next code I can not make the toast message inside the doInBackground method jump.
When I delete this line, the writing of the "error" string into the edittext performed fine.
What am I doing wrong?
private class Verify extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
username = etusername.getText().toString();
password = etpass.getText().toString();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
postParameters.add(new BasicNameValuePair("password", password));
String response = null;
String result;
try {
response = CustumHttpClient.executeHttpPost(url_verify_detials, postParameters);
result = response.toString();
result = result.replaceAll("\\s+", "");
if (!result.equals("0")) {
Intent in = new Intent(MainActivity.this, danpage.class);
startActivity(in);
} else {
Toast.makeText(getApplicationContext(), "this is my Toast message!!", Toast.LENGTH_LONG)
.show();
etusername.setText("Error");
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
You can't place any code which does anything to the user interface inside the doInBackground method. If you want to show your toast you will need to return a result to onPostExecute and deal with it there.
How do you return a result to onPostExecute? In your class definition the third parameter inside the <> is the type that you will want to return in the onPostExecute method so you declaration will look like
private class Verify extends AsyncTask<Void, Void, String>
and you onPostExecute will look like
protected void onPostExecute(String result) {
Please see the reference for a good example. http://developer.android.com/reference/android/os/AsyncTask.html
You can use publishProgress and onProgressUpdate to make a Toast:
private static final int ERROR = -1;
...
try {
response = CustumHttpClient.executeHttpPost(url_verify_detials, postParameters);
result = response.toString();
result = result.replaceAll("\\s+", "");
if (!result.equals("0")) {
Intent in = new Intent(MainActivity.this, danpage.class);
startActivity(in);
} else {
//Toast.makeText(getApplicationContext(), "this is my Toast message!!", Toast.LENGTH_LONG)
// .show();
//etusername.setText("Error");
publishProgress(ERROR);
}
} catch (Exception e) {
}
...
#Override protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (values[0]==ERROR){
Toast.makeText(MainActivity.this, "this is my Toast message!!", Toast.LENGTH_LONG)
.show();
etusername.setText("Error");
}
}
You must use runOnUIThread method to execute this code.
You must execute ui methods in that thread.
Yeap ... toast has to be displayed on the UI thread. When you don't return a result from doInBackground you can return a Boolean instead and use it in onPostExecute to show your Toast. onPostExecute is executed on the UI thread. runOnUIThread is also a solution ...

POST request from real android device

I working on android application which post its location to server. Here's one problem.
When I run this application in genymotion, it succesfully send POST requests to server. However, when I installed on samsung galaxy note, it doesn't send these post requests.
Where can be the problem?
EDIT: I successfully can fetch data from internet by GET request
Code:
class Posting extends AsyncTask<Location, String, String>{
#Override
protected void onPreExecute(){
}
#Override
protected String doInBackground(Location... locations){
RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(RetrofitClient.API_URL2).build();
RetrofitClient.TestRetro retrofit = restAdapter.create(RetrofitClient.TestRetro.class);
IssdDeviceLog body=new IssdDeviceLog();
body.setDeviceNo("hello from SAMSUNG MAIN ACTIVITY service");
body.setLatitude(new BigDecimal(locations[0].getLatitude()));
body.setLongtitude(new BigDecimal(locations[0].getLongitude()));
Date date= new Date();
body.setDate(date.toString());
Gson gson = new Gson();
String json = gson.toJson(body);
Response response=retrofit.sendLocation(json);
Log.d("status code"," "+response.getStatus());
return null;
}
#Override
protected void onPostExecute(String file_url) {
}
}
With regards
can you put your error if you getting any error or you can use volley library i am sharing this code you can use this for your post request
public class send_data extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(main.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setTitle("please wait...");
mProgressDialog.show();
}
protected String doInBackground(String... args) {
String url = "http://your_url";
try {
ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>(
1);
nvp.add(new BasicNameValuePair("key for your data","yourdata"));
String str_responsebody = obj_service.executer(url, nvp);
Log.i("responce", str_responsebody + "===");
return str_responsebody;
} catch (Exception e) {
Log.i("error1", "" + e.toString());
return null;
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Log.i("result", result);
mProgressDialog.dismiss();
}
} catch (Exception e) {
Log.e("error2", "" + e.toString());
e.printStackTrace();
mProgressDialog.dismiss();
}
}
}
download volley lib and add in your project. tutorial [link]: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Categories

Resources