How to confirm a log in Android? - 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();
}
}
}

Related

AsyncTask doInBackGround is not called

I've created an AsyncTask for my app but doinbackground method is not called upon onpreexecute. Here is my code:
public class NewProductActivity extends AsyncTask<String,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(context, "Please wait", "Sending data...", true);
}
#Override
protected Boolean doInBackground(String... params) {
try {
boolean added = dbo.addDataToDB(name, pass);
Log.d("1234rrr", name +" "+pass);
return added;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(context, "successfully added.", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "failed to add data.", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
}
And here is how I call it:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new NewProductActivity(UserName.getText().toString(), Password.getText().toString(), this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
new NewProductActivity(UserName.getText().toString(),Password.getText().toString(),this).execute();
But the app is stuck on onpreexecute. By the way I have only one asynctask. Can anyone help me with this situation? Thanks!
Edit:
I've realized that when I put the log message in the first line of doinbackground I get the message. I'm guessing the problem is with addDataToDB function. Here is the code for addDataToDB:
public boolean addDataToDB(String name, String pass){
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.sample.com/phpfilelocation/insertData.php");
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httpPost);
return true;
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
catch(Exception e){
e.printStackTrace();
return false;
}
}

Async running twice

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

Android Login with HTTP post, get results

I am trying to create a Login function so i can verify the users. I pass the Username , Password variables to AsyncTask class but i don't know hot to get results in order to use them. Any help? (I am posting part of the source code due to website restrictions)
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(txtUsername.getText().toString().trim().length() > 0 && txtPassword.getText().toString().trim().length() > 0)
{
// Retrieve the text entered from the EditText
String Username = txtUsername.getText().toString();
String Password = txtPassword.getText().toString();
/*Toast.makeText(MainActivity.this,
Username +" + " + Password+" \n Ready for step to post data", Toast.LENGTH_LONG).show();*/
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
new PostDataAsyncTask().execute(params);
// Redirect to dashboard / home screen.
login.dismiss();
}
else
{
Toast.makeText(MainActivity.this,
"Please enter Username and Password", Toast.LENGTH_LONG).show();
}
}
});
Then i use the AsynkTask to do the check but do not know how to get the results and store them in a variable. Any help?
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... params) {
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
String line = null;
String fail = "notok";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
line = resEntity.toString();
Log.v(TAG, "Testing response: " + line);
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
Intent Hotels_btn_pressed = new Intent(MainActivity.this, Hotels.class);
startActivity(Hotels_btn_pressed);
// you can add an if statement here and do other actions based on the response
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}else{
finish();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
Not the best code refactoring, but just to give you a hint.
I would create an interface (lets call it 'LogInListener'):
public interface LoginListener {
void onSuccessfulLogin(String response);
void onFailedLogin(String response);
}
The 'MainActivity' class would implement that interface and set itself as a listener the 'PostDataAsyncTask'. So, creating the async task from the main activity would look like this:
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
PostDataAsyncTask postTask = new PostDataAsyncTask(this);
postTask.execute(params);
I would move 'PostDataAsyncTask' class into a new file:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
private static final String ERROR_RESPONSE = "notok";
private LoginListener listener = null;
public PostDataAsyncTask(LoginListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
String postResponse = "";
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
postResponse = EntityUtils.toString(resEntity).trim();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
#Override
protected void onPostExecute(String postResponse) {
if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
listener.onFailedLogin(postResponse);
} else {
listener.onSuccessfulLogin(postResponse);
}
}
}
So, 'doInBackground' returns the response to 'onPostExecute' (which runs on the UI thread), and 'onPostExecute' routes the result (success or failure) to the MainActivity, which implements the 'LogInListener' methods:
#Override
public void onSuccessfulLogin(String response) {
// you have access to the ui thread here - do whatever you want on suscess
// I'm just assuming that you'd like to start that activity
Intent Hotels_btn_pressed = new Intent(this, Hotels.class);
startActivity(Hotels_btn_pressed);
}
#Override
public void onFailedLogin(String response) {
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}
I just assumed that that's what you wanted to do on success: start a new activity, and show a toast on fail.

Checking user details on login Android

I'm trying to make a login system for my application. Currently the user can create an account online and download the app. They are then prompted for their username and password.
When they press the login button I want to make a request to a php script on the server to check the results and return true if the user does exist and false if they do not exist.
I am a little bit confused about how I should implement this?
I am trying to create a seperate class that extends AsyncTask.
This is my MainActivity
EditText username;
EditText password;
Button loginBtn;
LinearLayout loginform;
String passwordDetail;
String usernameDetail;
String url = "http://www.jdiadt.com/example/checklogindetails.php";
HttpTask httptask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide the Action Bar
ActionBar ab;
ab = this.getActionBar();
ab.hide();
//Get references to XML
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
loginBtn = (Button)findViewById(R.id.loginBtn);
loginform = (LinearLayout)findViewById(R.id.loginform);
//Animation
final AlphaAnimation fadeIn = new AlphaAnimation(0.0f , 1.0f );
AlphaAnimation fadeOut = new AlphaAnimation( 1.0f , 0.0f ) ;
fadeIn.setDuration(1200);
fadeIn.setFillAfter(true);
fadeOut.setDuration(1200);
fadeOut.setFillAfter(true);
fadeOut.setStartOffset(4200+fadeIn.getStartOffset());
//Run thread after 2 seconds to start Animation
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run() {
//display login form
loginform.startAnimation(fadeIn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//display();
Toast.makeText(getApplicationContext(), "Checking login details...", Toast.LENGTH_SHORT).show();
if(checkLoginDetails()){
//OPENS NEW ACTIVITY
//Close splash screen
finish();
//start home screen
Intent intent = new Intent(v.getContext(), SectionsActivity.class);
startActivity(intent);
//creates fade in animation between two activities
overridePendingTransition(R.anim.fade_in, R.anim.splash_fade_out);
}
else{
}
}
});
}
}, 2000);
}
//Check the login details before proceeding.
public boolean checkLoginDetails(){
usernameDetail = username.getText().toString();
passwordDetail = password.getText().toString();
httptask = new HttpTask();
httptask.execute(url, usernameDetail, passwordDetail);
//if exists return true
//else return false
return false;
}
}
This is my HttpTask
public class HttpTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
String url = params[0];
String username = params[1];
String password = params[2];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
try {
httpClient.execute(httpPost);
return true;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my php script on my webserver checklogindetails.php
require_once 'db_connect.php';
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$pwdMD5 = md5($password);
$sql = "SELECT * FROM users WHERE username = '$username' AND password='$pwdMD5'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
echo "Log in successful";
//RETURN TRUE
}
else{
echo "Wrong username or password";
//RETURN FALSE
}
I guess the place I'm most confused about is how to constuct the php script to check the login details and how I can decide what to do based on it returning true or false.
I'd appreciate any advice or help on this subject! Many thanks
The above code looks good except that you are missing the last step.
Returning something from the PHP and then reading it in the app.
I would suggest changing the output of the PHP to something easier to parse/maintain like "OK" and "ERROR"
Then add the following code to the HttpTask.
final HttpResponse response = httpClient.execute(httpPost, localContext);
if (response != null)
{
// parse response
final HttpEntity entity = response.getEntity();
if (entity == null)
{
// response is empty, this seems an error in your use case
if (BuildConfig.DEBUG)
{
Log.d(HttpClient.TAG, "Response has no body"); //$NON-NLS-1$
}
}
else
{
try
{
// convert response to string
this.mResponseAsString = EntityUtils.toString(entity);
if (BuildConfig.DEBUG)
{
Log.d(HttpClient.TAG, "Response: " + this.mResponseAsString); //$NON-NLS-1$
}
// parse the string (assuming OK and ERROR as possible responses)
if (this.mResponseAsString != null && this.mResponseAsString.equals("OK")
{
// add happy path code here
}
else
{
// add sad path here
}
}
catch (final ParseException e)
{
Log.e(HttpClient.TAG, e.getMessage(), e);
}
catch (final IOException e)
{
Log.e(HttpClient.TAG, e.getMessage(), e);
}
}
this.mResponseCode = response.getStatusLine().getStatusCode();
}
Personally I would also refactor the "OK" in the HttpTask to a constant (for easy reading and maintaining) and also refactor most the HTTP based code to some kind of base class or utility class so you can reuse it.

ProgressDialog doesn't show the real progress of fetching information from a web server

I transferred my code of fetching some information into an Async class, it is to minimize the buffering and avoid the possibility of 'not responding', or worse crashing of my application.
Now, I want to show a ProgressDialog, and it should be set to 'not cancelable' to avoid users of interrupting the connection.
But I am a little confused if my ProgressDialog really show the progress of what actually happens in my application (during the fetching of information from an online server). Because on my emulator, my application pauses (for about 2 seconds), and then shows the ProgressDialog, and then immediately shows the result of the 'fetching'.
Any help will be much appreciated.
Thanks. Here's my code.
public void onClick(View v)
{
new retrieveOnline().execute();
}
private class retrieveOnline extends AsyncTask <Void, Void, Void>
{
protected void onPreExecute ()
{
pDialog = new ProgressDialog (FirstScreen.this);
pDialog.setMessage("Please wait...");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... unused)
{
runOnUiThread (new Runnable()
{
public void run()
{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://mysite.com/database/login.php");
stringEmail = etEmail.getText().toString();
stringPassword = etPassword.getText().toString();
try
{
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("stringEmail", stringEmail));
nameValuePairs.add(new BasicNameValuePair("stringPassword", stringPassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()== 200)
{
entity = response.getEntity();
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
String errorEmail = jsonResponse.getString("errorEmail");
if (errorEmail != "")
{
tvEmailError.setText(errorEmail);
}else{}
String errorPassword = jsonResponse.getString("errorPassword");
if (errorPassword != "")
{
tvPasswordError.setText(errorPassword);
}else{}
String inactiveAccount = jsonResponse.getString("inactiveAccount");
if (inactiveAccount.length() != 0)
{
AlertDialog alert = new AlertDialog.Builder(FirstScreen.this).create();
alert.setCancelable(false);
alert.setMessage("Your account is currently inactive and unusable." + "\nDo you want to send an account activation message to your email now?");
alert.setButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://mysite.com/database/activate2.php");
stringEmail = etEmail.getText().toString();
stringPassword = etPassword.getText().toString();
try
{
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("stringEmail", stringEmail));
nameValuePairs.add(new BasicNameValuePair("stringPassword", stringPassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()== 200)
{
entity = response.getEntity();
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
String successActivation = jsonResponse.getString("successActivation");
if (successActivation.length() != 0)
{
//Progress Dialog here.
Toast.makeText(getBaseContext(), "We successfully sent an activation message to your email account. Try to log in again after activating your account.", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, we are unable to reach your email account.",Toast.LENGTH_SHORT).show();
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
}
}
});
alert.setButton2("Not now", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
AlertDialog alert2 = new AlertDialog.Builder(FirstScreen.this).create();
alert2.setCancelable(false);
alert2.setMessage("Exit FindDroid?");
alert2.setButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
finish();
}
});
alert2.setButton2("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//Do nothing
}
});
alert2.show();
}
});
alert.show();
}else{}
if ((errorEmail.length()==0) && (errorPassword.length()==0)&& (inactiveAccount.length()==0))
{
String dbEmail = jsonResponse.getString("dbEmail");
String dbPassword = jsonResponse.getString("dbPassword");
//---Store dbEmail and dbPassword to SharedPreferences---//
//-------------------------------------------------------//
Intent i = new Intent(getApplicationContext(), Construction.class);
startActivity(i);
finish();
}
}//if (entity!=null)..
}//if response()...
}//try..
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
}
}
});
return (null);
}
protected void onPostExecute (Void unused)
{
pDialog.dismiss();
}
}
I am making a log in activity, and it's getting the registered users information from an online server..
Ok, so what you have here is an AsyncTask that immediately creates a runnable that runs on the UI thread, completely defeating the purpose of the AsyncTask. Get rid of the runOnUIThread, do all the processing in the background call and use the OnProgressUpdate and OnPostExecute to update the UI. Also ready the API documentation here:
http://developer.android.com/reference/android/os/AsyncTask.html
The ProgressDialog doesn't automatically update, you need to update it in the OnProgressUpdate call from your AsyncTask.
Yes, call publishProgress from doInBackground with an integer to pass to pDialog.setProgress(int) Alter the AsyncTask signature to pass the integer <Void, Integer, Void> You'll want to normalize that progress integer between 0-10000 before passing to onProgressUpdate This can be done when loading an image or a large amount of data from the web by loop through bytes or lines, reading in chunks, and passing progress update as you go.
Another thing you need to modify, is you CANNOT access/modify/touch-in-any-way objects in the UI during doInBackground You'll need to move things like alert.show() Toast and I beleive the Activity methods also (ie. finish()) to the postExecute method.

Categories

Resources