![here there are 3 edit text box. where i am using json to check the login id and password details and another text box is for the selection of the server address. the only criteria is that all these should be done with a single button ie the login button.
can any one help me with the code]1
the code is as follows
package com.example.catxam;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.catxam.JSONParser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class Login extends Activity {
private EditText inputUserid, inputPassword, server;
TextView forgotPassword;
private Button b1;
public String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.login);
inputUserid = (EditText) findViewById(R.id.Username_edit);
inputPassword = (EditText) findViewById(R.id.User_password);
server = (EditText) findViewById(R.id.serverSelection);
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent passForget = new Intent(getApplicationContext(),
ForgotPassword.class);
startActivity(passForget);
}
});
b1 = (Button) findViewById(R.id.loginbutton); // login button
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new CreateNewUser().execute();
new SelectServerAddress().execute();
}
});
}
// this class is for selection of the server address
class SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
return null;
}
}
// this class is for the checking of the user login and password
//i.e. of first login and the next consecutive logins
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Checking..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking creditenials
* */
protected String doInBackground(String... args) {
String user = inputUserid.getText().toString();
String pswrd = inputPassword.getText().toString();
//if (serve == "")
//{
//serve = "192.168.0.101/gly_prov_V1";
//}
//else
//{
//serve = "glydenlewis.esy.es";
//}
// URL to check username & password
final String url_check_user = "http://" + serve +"/gly_prov_V1/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
params.add(new BasicNameValuePair("server",serve));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_check_user,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
int flag_ck = json.getInt(Flag);
if (success == 1) {
if (flag_ck == 0)
{
//First Time Login By User
Intent i = new Intent(getApplicationContext(), UpdateDetails.class);
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
You can execute tasks in serial manner. Take the output of first task as input to the second task.
But you have to implement a cancel mechanism if the activity is destroyed while your tasks is actually running. a simple approach is to make tasks references as a class member and cancel it when activity's onStop() method is called.
class static SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... urls) {
return getAddress(urls[0]);
}
#Override
protected void onPostExecute(String serverAddress) {
// Call login service
mLoginTask = new CreateNewUser(serverAddress);
mLoginTask.execute();
}
}
Edit:
Update button click listener code to this:
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SelectServerAdress().execute();
}
});
Then update SelectServerAdress class and add this method:
#Override
protected void onPostExecute(String serverAddress) {
serve = serverAddress;
new SelectServerAddress().execute();
}
Related
I am running a long running process (which is an servlet call) inside an AsyncTask doInBackground which may run for more than 5 minutes. But after 5 minutes the servlet is returned and I am getting a timeout problem.
Below is my code:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.example.hanamom.LoginActivity.GetXMLTask;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.ProgressDialog;
public class NewInstallationActivity extends Activity {
Button install;
EditText branch_enter;
EditText cl_enter;
EditText sid_enter;
EditText sidpwd_enter;
EditText systempwd_enter;
EditText instance_enter;
EditText installationlocation_enter;
Bundle extras;
EditText desc_enter;
ProgressDialog pd;
public static final String URL = "<a servlet call>";
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
Intent intent;
String login_user,host,rootuser,rootpassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.install);
addListenerOnButton();
Log.e("test", "Entered New Instlalaiton activity");
branch_enter = (EditText) findViewById(R.id.branch_enter);
cl_enter = (EditText) findViewById(R.id.cl_enter);
sid_enter = (EditText) findViewById(R.id.sid_enter);
sidpwd_enter = (EditText) findViewById(R.id.sidpwd_enter);
systempwd_enter = (EditText) findViewById(R.id.systempwd_enter);
instance_enter=(EditText) findViewById(R.id.instance_enter);
installationlocation_enter=(EditText) findViewById(R.id.installationlocation_enter);
Bundle extras = this.getIntent().getExtras();
login_user=extras.getString("login_user").trim();
host = extras.getString("promptshost");
rootuser = extras.getString("lrootUser");
rootpassword = extras.getString("lrootpwd");
Log.e("login user",login_user);
Log.e("rootuser=",rootuser);
Log.e("rootpassword=",rootpassword);
}
private void addListenerOnButton() {
// TODO Auto-generated method stub
final Context context = this;
branch_enter = (EditText) findViewById(R.id.branch_enter);
cl_enter = (EditText) findViewById(R.id.cl_enter);
sid_enter = (EditText) findViewById(R.id.sid_enter);
sidpwd_enter = (EditText) findViewById(R.id.sidpwd_enter);
systempwd_enter = (EditText) findViewById(R.id.systempwd_enter);
instance_enter=(EditText) findViewById(R.id.instance_enter);
installationlocation_enter=(EditText) findViewById(R.id.installationlocation_enter);
install = (Button) findViewById(R.id.install);
install.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
});
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
String response = "false";
private ProgressDialog pd;
protected void onPreExecute() {
pd = new ProgressDialog(NewInstallationActivity.this);
pd.setMessage("Please wait while SAP HANA system is being Installed..");
pd.setIndeterminate(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.show();
}
protected String doInBackground(String... urls) {
try {
Log.e("NewInstallationActivty", "New installation");
String branch=branch_enter.getText().toString();
String cl = cl_enter.getText().toString();
String sid=sid_enter.getText().toString();
String sidpwd=sidpwd_enter.getText().toString();
String systempwd=systempwd_enter.getText().toString();
String instance=instance_enter.getText().toString();
String installationlocation=installationlocation_enter.getText().toString();
Log.e("Branch=",branch);
Log.e("Host=",host);
Log.e("sid=",sid);
Log.e("sidpwd=",sidpwd);
Log.e("systempwd=",systempwd);
Log.e("instance=",instance);
Log.e("installationlocation=",installationlocation);
Log.e("rootuser=",rootuser);
Log.e("rootpassword=",rootpassword);
// String osuser=osuser_enter.getText().toString();
// String ospassword=ospassword_enter.getText().toString();
Log.e("NewInstlalationActivity", "installtion");
postParameters.add(new BasicNameValuePair("branch",branch));
postParameters.add(new BasicNameValuePair("cl", cl));
postParameters.add(new BasicNameValuePair("sid", sid));
postParameters.add(new BasicNameValuePair("sidpwd", sidpwd));
postParameters.add(new BasicNameValuePair("systempwd",systempwd));
postParameters.add(new BasicNameValuePair("instance",instance));
postParameters.add(new BasicNameValuePair("installationlocation",installationlocation));
postParameters.add(new BasicNameValuePair("host",host));
postParameters.add(new BasicNameValuePair("rootuser", rootuser));
postParameters.add(new BasicNameValuePair("rootpassword", rootpassword));
postParameters.add(new BasicNameValuePair("intent","install"));
Log.e("NewInstlalationActivity", "post parameters");
for (String url : urls) {
response = CustomHttpClient.executeHttpPost(url,postParameters);
}
}
catch(Exception e) {}
return "Success";
}
protected void onPostExecute(String output) {
Log.e("Login Activity",response);
while(!response.trim().equals("True"))
{
pd.show();
pd.setProgress(100);
continue;
}
if (response.trim().equals("True"))
{
Log.e("Entered Response = True", response);
pd.dismiss();
Intent intent = new Intent(getBaseContext(), NewInstallationActivity.class);
startActivity(intent);
}
else
{
Log.e("Else code","Else");
AlertDialog alertDialog = new AlertDialog.Builder(
NewInstallationActivity.this).create();
alertDialog.setTitle("Installation Failed!");
// Setting Dialog Message
alertDialog.setMessage(" Check logs at /var/tmp");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
}
Here my process dialog will wait until I get a True from the servlet but exactly after 5 minutes, it is sending a false.
Is there any method to wait for more than 5 minutes. Any hint would be helpful.
Thanks.
You can try the following :
private final static long TIMETOWAIT = 30000; // Set your timeout.
....
GetXMLTask.get(TIMETOWAIT,TimeUnit.MILLISECONDS);
....
For reference :
http://developer.android.com/reference/android/os/AsyncTask.html#get%28long,%20java.util.concurrent.TimeUnit%29
I am trying to load a popup window that contains an edittext and a datepicker.
I have included my code below.
Basically the initial window is closed as expected, but my pop up doesn't appear?
I have checked the xml call and the id is correct, no errors and for some reason my logcat in eclipse has stopped working but thats a different issue!
Hopefully someone can tell me what I have missed and / or doing wrong? I am new to android programming so please ignore my ignorance if it is something simple!
package com.zelphe.zelpheapp;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.zelphe.zelpheapp.library.DatabaseHandler;
import com.zelphe.zelpheapp.library.UserFunctions;
public class LoginActivity extends Activity
{
Button btnLogin;
Button Btnregister;
Button passreset;
EditText inputEmail, inputName, inputPassword;
DatePicker inputDOB;
private TextView loginErrorMsg;
/**
* Called when the activity is first created.
*/
private static String KEY_SUCCESS = "success";
private static String KEY_REGISTER = "doRegister";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
Button btnReg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_test);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.loginbtn);
//loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
/**
* Login button click event
* A Toast is set to alert when the Email and Password field is empty
**/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(LoginActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
}else if(Integer.parseInt(res) == 2)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Incorrect Password!", Toast.LENGTH_SHORT).show();
}
else
{
pDialog.dismiss();
initiatePopupWindow();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private PopupWindow pwindo;
private void initiatePopupWindow()
{
try
{
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) LoginActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_register,(ViewGroup)
findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 350, 350, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnReg = (Button) layout.findViewById(R.id.btnReg);
btnReg.setOnClickListener((android.view.View.OnClickListener) reguser);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private OnClickListener reguser = new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
inputName = (EditText) findViewById(R.id.name);
inputDOB = (DatePicker) findViewById(R.id.dob);
if ( ( !inputName.getText().toString().equals("")) &&
( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) > 15) )
{
//register user
}
else if ( ( inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
else if (( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) < 16) )
{
Toast.makeText(getApplicationContext(),
"You must be at least 16 to use this app", Toast.LENGTH_SHORT).show();
}
}
};
}
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
Embarassingly enough, there is no issue with the popup, I had an error further up in my code, doh!
I get an error on line 80 (userFunction.logoutUser(getApplicationContext());) That says userFunction cannot be resolved. I have defined userFunction and have already tried to use the full package name and things, so what can I do to get rid of this error really quick? (Asked this question mostly for future reference since this happens a lot) Thanks!
package com.example.dashboardactivity;
import libary.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginActivity extends Activity {
public final String TAG = "LoginActivity";
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
Log.i(TAG, "LoginActivity Login button Click Event" );
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new AsyncTask<String, Void, JSONObject>(){
#Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
String email = args[0];
String password = args[1];
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) { //This is run on the UI thread
if(json != null){
//... update the user interface ...
Log.i(TAG, "checking for login response");
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
libary.DatabaseHandler db = new libary.DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Log.e("LoginTask", "No login response was received");
}
super.onPostExecute(json);
}
}.execute(inputEmail.getText().toString(), inputPassword.getText().toString());
}
});
// Link to Register Screen
Log.i(TAG, "LoginActivity btnLinkToRegister" );
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
You've defined UserFunctions userFunction = new UserFunctions(); inside the doInBackground method but are trying to access the variable in onPostExecute.
Try to declare UserFunctions userFunction; outside the doInBackground so that it is accessible to other functions.
new AsyncTask<String, Void, JSONObject>(){
UserFunctions userFunction;
#Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
userFunction = new UserFunctions();
}
#Override
protected void onPostExecute(JSONObject json) {
userFunction.logoutUser(getApplicationContext());
}
}
I am creating simple system that has a windows service running, complete with a table of users, and I want to validate someone's login credentials by sending something to the service. I am trying to send their username and password, but I keep getting an error with my Async Task. I know that you're not supposed to mess with UI stuff in there and I am not. Originally I had a call to another activity in there but I commented it out. Now the only thing in doInBackground is setting a boolean value to true if the validation was good. From there I read the value after the async has executed, and then put together a bundle to move to the next place. I just don't know what's wrong here. It has been awhile since I've programmed in Android so maybe I'm missing something stupid. If anyone could help me out I would greatly appreciate it! Thank you. This could also be an issue with sending the information to the service?
UPDATE: After adding in the internet usage in the manifest, if I have the log.d in the program in my doInBackground, it prints out. If I don't have it, the result value stays false. It looks like there is some issue with the connection between my service and android app...
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private static final int DATA_FROM_MAIN_ACTIVITY = 1;
private static final String SERVICEURL = "http://localhost:56638/ClientService.svc";
private EditText userTextBox, passTextBox;
private Button loginButton;
private String uName, pass;
private Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userTextBox = (EditText) findViewById(R.id.userTextBox);
passTextBox = (EditText) findViewById(R.id.passTextBox);
loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uName = userTextBox.getText().toString();
pass = passTextBox.getText().toString();
SendLoginMessage task = new SendLoginMessage();
task.execute(uName, pass);
if (result.equals(true)) {
Intent goToMainScreen = new Intent(getApplicationContext(),
MainActivity.class);
goToMainScreen.putExtra("username", uName);
goToMainScreen.putExtra("password", pass);
startActivityForResult(goToMainScreen,
DATA_FROM_MAIN_ACTIVITY);
} else {
Toast.makeText(
getApplicationContext(),
"There was an issue with your username or password.",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class SendLoginMessage extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// Log.d("message almost at server, " + textFromArea, selected,
// null);
}
#Override
protected Void doInBackground(String... names) {
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", names[0]));
postParams.add(new BasicNameValuePair("password", names[1]));
String response = null;
try {
response = HttpClient.executeHttpPost(SERVICEURL, postParams);
String newResponse = response.toString();
newResponse = newResponse.replaceAll("\\s+", "");
// if user was authenticated...
if (newResponse.equals(true)) {
result = true;
// creating an intent to take user to next page.
// load their DB objects on the
// on create in other activity
// pass the username/password to next activity
// then make a request to the server for their database
// objects.
// Intent goToMainScreen = new
// Intent(getApplicationContext(), MainActivity.class);
// goToMainScreen.putExtra("username", names[0]);
// goToMainScreen.putExtra("password", names[1]);
// startActivityForResult(goToMainScreen,
// DATA_FROM_MAIN_ACTIVITY);
}
} catch (Exception e) {
Log.d("ERROR", "exception in background");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Toast.makeText(getApplicationContext(),
// .show();
}
}
}
Do it like this:
private class SendLoginMessage extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... names) {
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", names[0]));
postParams.add(new BasicNameValuePair("password", names[1]));
String response = null;
try {
response = HttpClient.executeHttpPost(SERVICEURL, postParams);
String newResponse = response.toString();
newResponse = newResponse.replaceAll("\\s+", "");
// if user was authenticated...
if (newResponse.equals("true")) {
return true;
}
} catch (Exception e) {
Log.d("ERROR", "exception in background");
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Intent goToMainScreen = new Intent(getApplicationContext(),
MainActivity.class);
goToMainScreen.putExtra("username", uName);
goToMainScreen.putExtra("password", pass);
startActivityForResult(goToMainScreen,
DATA_FROM_MAIN_ACTIVITY);
} else {
Toast.makeText(
getApplicationContext(),
"There was an issue with your username or password.",
Toast.LENGTH_LONG).show();
}
}
}
and in your onClick() just call execute()
uName = userTextBox.getText().toString();
pass = passTextBox.getText().toString();
SendLoginMessage task = new SendLoginMessage();
task.execute(uName, pass);
After execution is finished onPostExecute() will be called and your Activity will start depending on result variable.
Don't check your result variable after you invoke execute() because execute() is invoked asynchronously. By the time you check your global result variable, your doInBackground() might not have been finished. Using my approach you don't need a global variable. Please read doc carefully before using any component.
I have this async Task on android 2.3.5
class InternetConnexionErrorAsync extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
mdpiImageView.setClickable(false);
journalsImageView.setClickable(false);
accountImageView.setClickable(false);
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... aurl) {
try {
Thread.sleep(3450);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused)
{
finish();
}
}
Everything is working well.
When I try this in Android 4.0, I am newer accessint the onPostExecute.
Could you please help me. No error message, only that the onPostExecute is newer reached.
Whatever you need to update on the UI you need to do in onPostExecute.
The code below, take a look at onPostExecute - specifically the activity.xx() methods send updates to the main activity that do things on the UI.
For example:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import library.DatabaseHandler;
import library.JSONParser;
import library.UserFunctions;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
private Polling activity;
private int id = -1;
private JSONParser jsonParser;
private static String loginURL = "http://davidjkelley.net/android_api/";
private static String registerURL = "http://davidjkelley.net/android_api/";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private int responseCode = 0;
public LoginTask(Polling activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute()
{
progressDialog.show();
}
protected Integer doInBackground(String... arg0) {
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
String email = userName.getText().toString();
String password = passwordEdit.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
//user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(activity.getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
//Log.v("name", json_user.getString(KEY_NAME));
// Clear all previous data in database
userFunction.logoutUser(activity.getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL),
json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
responseCode = 1;
// Close Login Screen
//finish();
}else{
responseCode = 0;
// Error in login
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode)
{
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
if (responseCode == 1) {
progressDialog.dismiss();
activity.loginReport(responseCode);
userName.setText("");
passwordEdit.setText("");
//shared prefences, store name
}
if (responseCode == 0) {
progressDialog.dismiss();
activity.loginReport(responseCode);
}
//if(responseCode == 202)
//activity.login(id);
//else
//activity.showLoginError("");
}
}
Here's the main activity, you can see what loginReport does:
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
private Button loginButton;
private Button registerButton;
private CheckBox remember;
SharedPreferences sharedPreferences;
Toast toast;
ActionBar bar;
//DatabaseHandler ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
}
public void loginReport(int responseCode) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
UserFunctions userFunctions = new UserFunctions();
Context context = getApplicationContext();
//login succeeded, sent when LoginTask doInBg sends a 1 to onPostExecute
if (responseCode == 1) {
loginButton = (Button)findViewById(R.id.loginButton);
loginButton.setText("Log Out");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Logged in.", duration);
toast.show();
bar.getTabAt(0).setText(db.getUserDetails().get(db.KEY_EMAIL));
//Log.v(TAG, db.getUserDetails().toString());
}
//login failed, sent when LoginTask doInBg sends a 0 to onPostExecute
if (responseCode == 0) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Incorrect username/password", duration);
toast.show();
}
if (responseCode == 2) {
//logout button clicked, listened from within LoginFragment
//remove user from active sql db here rather than LoginFragment?!
bar.getTabAt(0).setText(R.string.login);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Logged out", duration);
toast.show();
userFunctions.logoutUser(context);
}
}
The solution I adopted, after the suggestion of #Davek804 is that I replace the AsyncTask with a delayed runable like this:
private Runnable mMyRunnable = new Runnable()
{
public void run()
{
finish();
}
};
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 3450);
So the effect will be the same.
I found the solution here
Instead of using :
task.execute();
use :
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);