I'm implementing pagination concept in my android application to store a very large
data in sqlite database.
I want to make a call to an API using retrofit.
The api will return a flag if we reach the end of the table. If yes I will store
result in local database if not make another (recursive call) until we reach the end of the table
Once I debugged it the api is called twice only while it should make another
call based on my logic.
The code reach the end of the OnResponse callback and it never get called again
public void getDataOffset (final int processType, final int offset) {
try {
progressDialog = ProgressDialog.show(activity, "Loading", "Upload ,
Please wait...", true);
String url = mUrl ;
Request request = new Request();
request.setEmployeeID(EmployID);
request.setOffset(offset);
IAPI iAPI = Global.getIAPI(url,420,420);
Call<RetrofitCallResponse.OffsetResponse> call = iAPI.GetDataOffset(request);
call.enqueue(new Callback<RetrofitCallResponse.OffsetResponse>() {
#Override
public void onResponse(Call<RetrofitCallResponse.OffsetResponse> call, Response<RetrofitCallResponse.OffsetResponse> response) {
if (response.isSuccessful() && response.body() != null) {
if (!response.body().HasError) {
if (response.body().DataList().size() <= 0) {
hasError = true;
errorMessage = "Empty.";
progressDialog.dismiss();
callback.onCallComplete(hasError,errorMessage);
}
mList.addAll(response.body().DataList());
if (response.body().IsEndOfTable) {
DBConnections dbConnections = new DBConnections(context, null);
boolean isInserted;
isInserted = dbConnections.insertOffset(mList,processType,context);
dbConnections.close();
if (!isInserted) {
hasError = true;
errorMessage = "Result couldn't be saved locally";
}
hasError = false;
progressDialog.dismiss();
callback.onCallComplete(hasError,errorMessage);
} else {
getDataOffset (processType , mList.size());
}
} else {
hasError = true;
errorMessage = response.body().ErrorMessage;
progressDialog.dismiss();
callback.onCallComplete(hasError,errorMessage);
}
} else {
progressDialog.dismiss();
hasError = true;
errorMessage = "Response Code : " + response.code() + " " + response.toString();
}
// progressDialog.dismiss();
// callback.onCallComplete(hasError,errorMessage);
}
#Override
public void onFailure(Call<RetrofitCallResponse.OffsetResponse> call, Throwable t) {
t.printStackTrace();
hasError = true;
errorMessage = t.toString();
progressDialog.dismiss();
callback.onCallComplete(hasError,errorMessage);
}
});
} catch (Exception e ) {
hasError = true;
errorMessage = e.toString();
callback.onCallComplete(hasError,errorMessage);
}
}
Related
I have a thread which is continuously running ,when i will send the command to get the data, data starts to come. I wanna to show this process to the Asynctask show that user can understand data is reading . How can i achieve this please help me . For now i am using timer. but timer will work for fixed time. but if my data is less, that time, timer will take the same time that i don't want . If anyone have any idea please let me know.... Thanks in advance for help
I had use this but because of running thread message getting continuously.
public static class Test extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
DataBaseController dataBaseController;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog( context);
progressDialog.setTitle( "Sync Data" );
progressDialog.setMessage( "Syncing..." );
progressDialog.setCancelable( false );
progressDialog.setIcon( android.R.drawable.ic_dialog_info );
progressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
dataBaseController = DataBaseController.getnstance( context );
// seperating the data which is getting from getResponse method
if (strings[0] != null) {
String ok = strings[0].replace( "OK", "" ).replace( "Scale id,Rec.No,Date,Time,Bill No.,Item No.,Plu,Name,Qty,Rate,Amount,Void", "" );
String[] data = ok.split( "," );
Log.i( "TEST", strings[0] );
for (int i = 0; i < data.length; i++) {
char c = strings[0].charAt( i );
if (c == ',') {
int id = Integer.parseInt( data[0] );
int rec_no = Integer.parseInt( (data[1]) );
String Date = data[2];
if (Date != null)
Date = custom_date_format( Date );
String Time = data[3];
int Bill_No = Integer.parseInt( data[4] );
int Item_No = Integer.parseInt( data[5] );
int Plu = Integer.parseInt( data[6] );
String Name = data[7];
String weight_type = data[8];
int Unit;
if (weight_type=="Kg"){
Unit=0;
}else{
Unit=1;
}
float Qty = Float.parseFloat( data[9] );
float Rate = Float.parseFloat( data[10] );
float Amount = Float.parseFloat( data[11] );
String Void = data[12];
PLU plu = new PLU( id, rec_no, Date, Time, Bill_No, Item_No, Plu, Name, Unit, Qty, Rate, Amount );
boolean check = dataBaseController.isBillExist( plu.getRec_no() );
if (!check) {
dataBaseController.Trasaction(plu);
}
}
}
}
return String.valueOf( strings );
}
#Override
protected void onPostExecute(String result) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (result != null) {
Toast.makeText( context, "Mission successfully", Toast.LENGTH_SHORT ).show();
}else{
Toast.makeText( context, "Mission failed", Toast.LENGTH_SHORT ).show();
}
}
}
*******Thread which is connected*****************
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
boolean get_actualdata = false;
private boolean stop = false;
private boolean hasReadAnything = false;
public ConnectedThread(BluetoothSocket socket) {
Log.d( TAG, "create ConnectedThread" );
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
// tmpIn.skip( 22 );
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e( TAG, "temp sockets not created", e );
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void shutdown() {
stop = true;
if (!hasReadAnything) return;
if (mmInStream != null) {
try {
mmInStream.close();
} catch (IOException e) {
Log.e( TAG, "close() of InputStream failed." );
}
}
}
public void run() {
boolean send_validation = true;
int version;
while (true) {
try {
version = readfunction(); // reading the version response after sending command on bluetooth
} catch (Exception e) {
e.printStackTrace();
connectionLost();
break;
}
if (version == 0) {
if (send_validation && !get_actualdata) {
StringParsing( str.toString() );// it will seperate the version
get_actualdata = true;
}
} else {
try {
readfunction();
} catch (IOException e) {
e.printStackTrace();
}
}
if (get_actualdata && send_validation) {
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
int ok = Handle_OK();//if getting ok
String status;
if (ok == 1) {
status = "OK";
mHandler.readLine( status );
} else {
status = "Not Recognised with device";
mHandler.readLine( status );
}
getReportResponse();
}
} catch (IOException e) {
connectionLost();
e.printStackTrace();
break;
}
}
}
}
//this method calling in running thread , it will response when command send by click on button
public void getReportResponse() throws IOException {
boolean with_header = false;
try {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( mmInStream ) );
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// String finalLine = line;
if (reset_the_reader_flag) { //if reset_the_header will true
with_header = false;
}
String f_line = custom_filter(line);
if (!f_line.isEmpty()){
if (with_header) { // if with_header flag will false then it will jump in else
// dataparse.ReportData( f_line);
new Handler( Looper.getMainLooper()).post( new Runnable() {
#Override
public void run() {
//Asynctask when command send this method will run
TabularFragment.Test data = new TabularFragment.Test();
data.execute( f_line );
}
} );
} else {
// if header matches set the with_header flag true, then exist from else part and again check with_heaer flag
// if header will not match, will jump in else and read the data that is without header.
if (f_line.matches( "Scale(.*)" )) {
with_header = true;
} else {//
dataparse.Data( f_line );
}
reset_the_reader_flag = false;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
mmInStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm using google sheets API with which I am creating new google sheets using sheets API, But this is using the account in which the sheet's API is enabled, If I give my app to another user he cannot create a new sheet using his Gmail. I have the API key, Is it possible to create sheets without selecting Gmail accounts
GoogleAccountCredential mCredential;
private static final String BUTTON_TEXT = "Call Google Sheets API";
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
private void getResultsFromApi() {
Log.d(TAG, "getResultsFromApi: ");
if (!isGooglePlayServicesAvailable()) {
Log.d(TAG, "getResultsFromApi: 1");
acquireGooglePlayServices();
} else if (mCredential.getSelectedAccountName() == null) {
Log.d(TAG, "getResultsFromApi: 2");
chooseAccount();
} else if (!isDeviceOnline()) {
Log.d(TAG, "getResultsFromApi: No network connection available.");
} else {
// x();
try {
new MakeRequestTask(mCredential).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
#AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void chooseAccount() {
if (EasyPermissions.hasPermissions(
this, Manifest.permission.GET_ACCOUNTS)) {
String accountName = getPreferences(Context.MODE_PRIVATE)
.getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
Log.d(TAG, "chooseAccount: 1");
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
} else {
Log.d(TAG, "chooseAccount: 2");
// Start a dialog from which the user can choose an account
startActivityForResult(
mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
} else {
// Request the GET_ACCOUNTS permission via a user dialog
EasyPermissions.requestPermissions(
this,
"This app needs to access your Google account (via Contacts).",
REQUEST_PERMISSION_GET_ACCOUNTS,
Manifest.permission.GET_ACCOUNTS);
}
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private com.google.api.services.sheets.v4.Sheets mService = null;
private Exception mLastError = null;
public MakeRequestTask(GoogleAccountCredential credential) throws IOException {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new com.google.api.services.sheets.v4.Sheets.Builder(
transport, jsonFactory, credential)
.setApplicationName("Google Sheets API Android Quickstart")
.build();
new Thread() {
#Override
public void run() {
try {
if (consurEtSurname.getText().toString().isEmpty()) {
consurEtSurname.setError("Please provide survey name!");
consurEtSurname.requestFocus();
} else {
Spreadsheet spreadsheet = new Spreadsheet()
.setProperties(new SpreadsheetProperties()
.setTitle(consurEtSurname.getText().toString()));
spreadsheet = mService.spreadsheets().create(spreadsheet)
.setFields("spreadsheetId")
.execute();
Makecolums(mService,spreadsheet.getSpreadsheetId());
upload(spreadsheet.getSpreadsheetId());
Log.d(TAG, "onCreate: " + spreadsheet.getSpreadsheetId());
Log.d(TAG, "run: " + spreadsheet.getSpreadsheetUrl());
}
// writeToSheetUsingApi(mService,spreadsheet.getSpreadsheetId());
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
// catch (GeneralSecurityException e) {
// e.printStackTrace();
// }
}
}.start();
}
//
// #Override
// protected List<String> doInBackground(Void... params) {
// try {
// return getDataFromApi();
// } catch (Exception e) {
// mLastError = e;
// cancel(true);
// return null;
// }
// }
//
//
// private List<String> getDataFromApi() throws IOException {
// String spreadsheetId = "196tcE1k5RuqTdGSBDpTFAI5h3m_dwXR875Q3csmi4ko";
// String range = "A1:X1";
//
// List<String> results = new ArrayList<String>();
// ValueRange response = this.mService.spreadsheets().values()
// .get(spreadsheetId, range)
// .execute();
//
// List<List<Object>> values = response.getValues();
// if (values != null) {
// for (int i = 0; i < values.size(); i++) {
// results.add(values.get(i).get(0) + ", " + values.get(i).get(1));
// }
// }
// return results;
// }
#Override
protected List<String> doInBackground(Void... voids) {
return null;
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
Log.d(TAG, "\"No results returned.\": ");
} else {
output.add(0, "Data retrieved using the Google Sheets API:");
Log.d(TAG, TextUtils.join("\n", output));
Log.d("TagOutputPost", TextUtils.join("\n", output));
}
}
#Override
protected void onCancelled() {
mProgress.hide();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
showGooglePlayServicesAvailabilityErrorDialog(
((GooglePlayServicesAvailabilityIOException) mLastError)
.getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) {
startActivityForResult(
((UserRecoverableAuthIOException) mLastError).getIntent(),
REQUEST_AUTHORIZATION);
} else {
Log.d(TAG, "The following error occurred:\n"
+ mLastError.getMessage());
}
} else {
Log.d(TAG, "Request onCancelled: ");
}
}
}
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
Log.d(TAG, "This app requires Google Play Services. Please install " +
"Google Play Services on your device and relaunch this app.");
} else {
getResultsFromApi();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.apply();
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
getResultsFromApi();
}
break;
}
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
return connectionStatusCode == ConnectionResult.SUCCESS;
}
private void acquireGooglePlayServices() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
}
}
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
Dialog dialog = apiAvailability.getErrorDialog(
ConfirmSurvey.this,
connectionStatusCode,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
#Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
#Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
}
So,I simply made a login screen where the data comes from an external server.
All of that happens in the background method.it all works correctly except for onPost and onPre methods.
I don't think they are doing their job.
while the onBackground method is running i would like to:
1.Show a message if the data is right or wrong.
2.Show a custom progress dialog i made while doinbackground is running.
But neither of them work,any ideas?
Here is my code!
public class DoLogin extends AsyncTask<String,String,String>
{
String message = "";
Boolean isSuccess = false;
String userid = dename.getText().toString();
String password = pass.getText().toString();
#Override
protected void onPreExecute() {
progressDialog.showProgress(SignInAr.this,"Loading...",false);
}
#Override
protected String doInBackground(String... params) {
new Thread(new Runnable() {
#Override
public void run() {
if(userid.trim().equals("")|| password.trim().equals(""))
message = "Please enter Username and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
message = "Error in connection with SQL server please contact the administrator";
isSuccess = false;
} else {
String query = "SELECT * FROM CustomerData where CustomerMobile='" + userid + "' and CustomerPassword='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
String id = rs.getString("CustomerID");
String mob = rs.getString("CustomerMobile");
String lng = getIntent().getStringExtra("lng");
String lat = getIntent().getStringExtra("lat");
message = "Welcome " + userid;
Intent intent = new Intent(SignInAr.this,agzakhana_mainAr.class);
intent.putExtra("lat",lat);
intent.putExtra("lng",lng);
intent.putExtra("nameid",id);
String getname = rs.getString("CustomerName");
intent.putExtra("nameofcus",getname);
intent.putExtra("mob",mob);
startActivity(intent);
finish();
isSuccess=true;
}
else
{
message = "Wrong info";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
message = "Exceptions"+ex;
}
}
}
}).start();
return message;
}
#Override
protected void onPostExecute(String r) {
progressDialog.hideProgress();
System.out.println("Message is: "+ r + "and isSuccess = "+ isSuccess);
if(!isSuccess) {
Toast.makeText(SignInAr.this,r,Toast.LENGTH_LONG).show();
}
}
}
Here is how i call the asynctask:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute();
}
});
You return value before thread run. Simple to fix it you shoukd remove Thread and Runnable in method doInBackground because in AsyncTask it already make doInBackground run in Background Thread.
Description: In OnRespose method i can see data received from froecast.io in log but when i am passing "response.body().string()" i.e. data from forecast.io as argument(string) to method getCurrentDetails then Method is receiving null and JSONObject is throwing null pointer Exception.
Tried: handle exception through multiple catch block.
double latitude = -122.423;
double longitude = 37.8267;
String apiKey = "cac63237c81f5312b496ed8cce991b40";
String forecastURL = "https://api.forecast.io/forecast/"+apiKey+"/"+longitude+","+latitude+"";
if(isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastURL).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
try {
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(response.body().string());
} else {
alertUserAboutProblem();
}
} catch (IOException e) {
Log.e(TAG, "Exception Caught: ", e);
}
catch(JSONException e){
Log.e(TAG,"Exception Caught: ", e);
}
}
});
Log.e(TAG, "Program is still running");
}
else{
Toast.makeText(MainActivity.this,"Network_Unavaliable",Toast.LENGTH_LONG).show();
}
}
private CurrentWeather getCurrentDetails(String string) throws JSONException {
------>>>>> JSONObject jsonObject = new JSONObject(string);
String timezone = jsonObject.getString("timezone");
JSONObject currently =jsonObject.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setPrecipIntensity(currently.getDouble("percipIntensity"));
currentWeather.setTimeZone(timezone);
Toast.makeText(MainActivity.this,String.valueOf(currently.getLong("time")),Toast.LENGTH_LONG).show();
// Log.d(TAG, String.valueOf(currentWeather.getTime()));
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo coninfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(coninfo!=null && coninfo.isConnected()){
isAvailable = true;
return isAvailable;
}
return false;
}
private void alertUserAboutProblem() {
AlertDialogFragment dialog =new AlertDialogFragment();
dialog.show(getFragmentManager(),TAG);
}
}
Try saving response.body().string() to a String variable and then passing it to getCurrentDetails.
Per the documentation: "the response body is a one-shot value that may be consumed only once".
Hi I am having a bit of trouble with the AsyncTask class for android. Here is my code for logging in a user on Parse. There are different cases such when the password is incorrect, etc.
My problem is that the error checking works and the different cases work fine but the progressDialog button will not go away after i close the alertdialog... Can anybody help me with this?
Here is my code
private class LoadTask extends AsyncTask<Map<String, String>, Integer, Void> {
// called before running code in a separate thread
private Result resultCode;
private boolean isSuccess;
private ProgressDialog progressDialog;
public LoadTask(Activity activity) {
onPreExecute();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TitlePage.this,
getString(R.string.login_progress_title),
getString(R.string.login_progress_message), false, false);
}
#Override
protected Void doInBackground(Map<String, String>... arg0) {
// Try to login with the given inputs
ParseUser user = null;
Map<String, String> argMap = arg0[0];
try {
user = ParseUser.logIn(argMap.get("username"), argMap.get("password"));
} catch (ParseException e) {
e.fillInStackTrace();
boolean errorOccured = false;
List<ParseObject> usernameResults = new ArrayList<ParseObject>();
List<ParseObject> passwordResults = new ArrayList<ParseObject>();
ParseQuery query = ParseUser.getQuery();
// try to find the username that the user typed in
query.whereEqualTo("username", argMap.get("username"));
try {
query.count();
usernameResults = query.find();
} catch (ParseException e1) {
// error occured trying to find the username
errorOccured = true;
e1.printStackTrace();
} catch (NullPointerException e1) {
errorOccured = true;
e1.printStackTrace();
}
// try to find the password that the user typed in
// associated with that username
query.whereEqualTo("username", argMap.get("username"));
query.whereEqualTo("password", argMap.get("password"));
try {
query.count();
passwordResults = query.find();
} catch (ParseException e1) {
// error occured trying to find the password
errorOccured = true;
e1.printStackTrace();
} catch (NullPointerException e1) {
errorOccured = true;
e1.printStackTrace();
}
// figure out the error
if (errorOccured) {
resultCode = Result.UNEXPECTED_ERROR;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
}
if ((usernameResults.size() == 0) && (passwordResults.size() == 0)) {
resultCode = Result.BOTH_INCORRECT;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_combo);
} else if ((usernameResults.size() == 0) && (passwordResults.size() != 0)) {
resultCode = Result.USERNAME_INCORRECT;
//buildAlertDialog(R.string.error_login_title, R.string.error_login_uname);
} else if ((usernameResults.size() != 0) && (passwordResults.size() == 0)) {
resultCode = Result.PASSWORD_INCORRECT;
//buildAlertDialog(R.string.error_login_title, R.string.error_login_pswd);
} else {
// unexpected error
resultCode = Result.UNEXPECTED_ERROR;
// buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
}
isSuccess = false;
return null;
}
// Check for verified email
boolean emailVerified = user.getBoolean("emailVerified");
if (!emailVerified) {
resultCode = Result.EMAIL_NOT_VERIFIED;
ParseUser.logOut();
}
isSuccess = true;
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
if (isSuccess) {
TitlePage.this.setReturnStatus(isSuccess);
} else {
System.out.println("THIS IS RESULT CODE " + resultCode);
if (resultCode == Result.UNEXPECTED_ERROR) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_unexp);
} else if (resultCode == Result.BOTH_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_combo);
} else if (resultCode == Result.USERNAME_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_uname);
} else if (resultCode == Result.PASSWORD_INCORRECT) {
buildAlertDialog(R.string.error_login_title, R.string.error_login_pswd);
} else {
buildAlertDialog(R.string.error_login_title, R.string.error_login_verif);
}
TitlePage.this.setReturnStatus(isSuccess);
}
}
}
And here is my code to run the async task in my main activity
Map<String, String> argMap = new HashMap<String, String>();
argMap.put("username", usernameString);
argMap.put("password", passwordString);
LoadTask task = new LoadTask(this);
task.execute(argMap);
private void buildAlertDialog(final int title, final int message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.close_alert, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
// if this button is clicked, close the dialog box
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show the message
alertDialog.show();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
Thank you
we can make progress dialog as same in the following example :
#Override
protected void onPreExecute() {
loadingDailog = new ProgressDialog(context,AlertDialog.THEME_HOLO_LIGHT);
((ProgressDialog) loadingDailog).setIndeterminate(true);
((ProgressDialog) loadingDailog).setProgressStyle(ProgressDialog.THEME_HOLO_LIGHT);
loadingDailog.setMessage("Loading...");
loadingDailog.show();
}
when you want to disapear this bar:
if (loadingDailog != null && loadingDailog.isShowing()) {
loadingDailog.dismiss();
}