Android Retrofit : Wait for response - android

I am implementing retrofit 2 in my app to call web services. My code is as below :
SignUp.java
ConnectionDetector connectionDetector = new ConnectionDetector(SignUpActivity.this);
if (connectionDetector.isConnectingToInternet()) {
ArrayList<HashMap<String, String>> arrayListCountryDetails = new ArrayList<>();
GetCountryList getCountryList = new GetCountryList();
arrayListCountryDetails = getCountryList.CallWebServiceForCountryDetails(this);
// The app should wait here till the above retrofit web service calling returns response
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(SignUpActivity.this, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
} else {
String message = "No internet connection.";
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(getResources().getString(R.string.app_name));
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
GetCountryList.java
public class GetCountryList {
ProgressDialog dialog;
APIService mAPIService;
ArrayList<HashMap<String, String>> arrayListCountryDetails;
public ArrayList<HashMap<String, String>> CallWebServiceForCountryDetails(final Context context) {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
arrayListCountryDetails = new ArrayList<>();
mAPIService = ApiUtils.getAPIService();
mAPIService.getCountryDetails().enqueue(new Callback<CountryDetailsResponseModel>() {
#Override
public void onResponse(Call<CountryDetailsResponseModel> call, Response<CountryDetailsResponseModel> response) {
if (response.isSuccessful()) {
HashMap<String, String> cntDetails = new HashMap<>();
cntDetails.put("airLineID", "0");
cntDetails.put("airLineName", "Select Airline");
arrayListCountryDetails.add(cntDetails);
// Get response
try {
if (response.body().getStatus() == 200 && response.body().getMessage().equalsIgnoreCase("success")) {
for (int count = 0; count < response.body().getCountry().size(); count++) {
cntDetails = new HashMap<>();
String countryID = response.body().getCountry().get(count).getCountryId();
String countryName = response.body().getCountry().get(count).getCountryName();
cntDetails.put("countryID", countryID);
cntDetails.put("countryName", countryName);
arrayListCountryDetails.add(cntDetails);
}
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
} else {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (Exception e) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
#Override
public void onFailure(Call<AirLineDetailsResponseModel> call, Throwable t) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
return arrayListCountryDetails;
}
}
When i am executing the code i am getting null pointer exception error as :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at com.abc.xyz.SignUpActivity.initializeScreen(SignUpActivity.java:176)
at com.abc.xyz.SignUpActivity.onCreate(SignUpActivity.java:147)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3278) 
at android.app.ActivityThread.access$1000(ActivityThread.java:211) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6912) 
at java.lang.reflect.Method.invoke(Native Method)
I know that this is because the spinner initialization execution is takes place before retrofit response.
Please suggest me how can i wait for the retrofit response. What changes i need to do in above code. Please i am not able to move ahead due to this issue.
Thanks in advance.

Very roughly do something like the following. I just placed the necessary part of code inside the AsyncTask methods. Modify as necessary.
if (connectionDetector.isConnectingToInternet()) {
// The app should wait here till the above retrofit web service calling returns response
AsyncTask task = new AsyncTask<Void, Void, List<Map<String, String>>>() {
#Override
protected String doInBackground(Void... params) {
List<Map<String, String>> arrayListCountryDetails = new ArrayList<>();
GetCountryList getCountryList = new GetCountryList();
arrayListCountryDetails = getCountryList.CallWebServiceForCountryDetails(this);
return arrayListCountryDetails;
}
#Override
protected void onPostExecute(List<Map<String, String>> arrayListCountryDetails) {
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(SignUpActivity.this, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
task.execute();
}
Also remove any UI calls from your GetCountryList since this will be run on "background"

Pass Spinner object while loading data and set adapter after load complete
public class GetCountryList {
ProgressDialog dialog;
APIService mAPIService;
public void CallWebServiceForCountryDetails(final Context context,final Spinner spinnerCountryName) {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
final ArrayList<HashMap<String, String>> arrayListCountryDetails = new ArrayList<>();
mAPIService = ApiUtils.getAPIService();
mAPIService.getCountryDetails().enqueue(new Callback<CountryDetailsResponseModel>() {
#Override
public void onResponse(Call<CountryDetailsResponseModel> call, Response<CountryDetailsResponseModel> response) {
if (response.isSuccessful()) {
HashMap<String, String> cntDetails = new HashMap<>();
cntDetails.put("airLineID", "0");
cntDetails.put("airLineName", "Select Airline");
arrayListCountryDetails.add(cntDetails);
// Get response
try {
if (response.body().getStatus() == 200 && response.body().getMessage().equalsIgnoreCase("success")) {
for (int count = 0; count < response.body().getCountry().size(); count++) {
cntDetails = new HashMap<>();
String countryID = response.body().getCountry().get(count).getCountryId();
String countryName = response.body().getCountry().get(count).getCountryName();
cntDetails.put("countryID", countryID);
cntDetails.put("countryName", countryName);
arrayListCountryDetails.add(cntDetails);
}
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
//set Adapter
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(context, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
} else {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (Exception e) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
#Override
public void onFailure(Call<AirLineDetailsResponseModel> call, Throwable t) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
}

Related

Android ProgressDialog shadow appears

In my android application calling an API continuously in a loop then Progress Dialog make a shadow like appearance. I think the issue is that multiple dialog running..help me to avoid this shadow. Code given below:
for(int i = indexOfSelectedId + 1 ; i < photoall_id.size(); i++)
{
all_postid.add(photoall_id.get(i));
url = URLS.BASEURL + "mobile_api.php?action=post&post_id=" +posoall_id.get(i)+user_id="+userid;
new GetImage().execute(url);
}
private class GetImage extends AsyncTask<String, Void, ArrayList<String>> {
String json = null;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
all_data=new ArrayList<>();
dialog = new ProgressDialog(FullScreenActivity.this);
dialog.setMessage("Loading Image...");
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> aVoid) {
dialog.dismiss();
all_url.add(aVoid.get(0));
}
#Override
protected ArrayList<String> doInBackground(String... params) {
JSONReader reader = new JSONReader();
json = reader.getJsonGET(params[0]);
if (json != null) {
try {
JSONObject object = new JSONObject(json);
if (object.getJSONArray("posts").getJSONObject(0).getInt("count") != 0) {
photo_url = object.getJSONArray("posts").getJSONObject(0).getString("photo_url");
}
}
Suggest a solution.Thanks in advance
To avoid multiple dialog to show:
public void showProgress(String msg)
{
if(dialog == null){
dialog = new ProgressDialog(this);
dialog.setTitle(null);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
}
if(dialog.isShowing())
{
dialog.dismiss();
}
dialog.setMessage(msg);
dialog.show();
}
public void dismissProgress()
{
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}

Wait for all the AsyncTask called in a loop are finished?

I'm calling async tasks in a loop on the onPostExecute() of an asyncTask. I want the control to wait until response of all the tasks is not receieved cause I'm collecting the response in a single arrayList which i have to pass a callback method after all the asyncTasks called in the loop are finished.
I'm avoiding to use the AsyncTask.get() as it blocks the main thread.
public class CallServerAsync extends AsyncTask<AsyncHttpRequestBo, Void, ArrayList<ArrayList<AsyncHttpRequestBo>>> implements PlatwareResponseListener {
PlatwareClientCommonUtils clientCommonFunctions;
Context context;
String url;
PlatwareResponseListener listener;
private ProgressDialog progressDialog;
ArrayList<AsyncHttpResponseBo> processResponseList = null;
ArrayList<AsyncHttpResponseBo> responseList = null;
public CallServerAsync(Context context, PlatwareResponseListener listener) {
this.context = context;
clientCommonFunctions = new PlatwareClientCommonUtils(context);
url = clientCommonFunctions.getServerUrlPrimary();
this.listener = listener;
responseList = new ArrayList<AsyncHttpResponseBo>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(context, "Please wait", "Downloading...");
}
#Override
protected ArrayList<ArrayList<AsyncHttpRequestBo>> doInBackground(AsyncHttpRequestBo... params) {
ArrayList<ArrayList<AsyncHttpRequestBo>> requestLists = clientCommonFunctions.generateRequestList(params);
return requestLists;
}
#Override
protected void onPostExecute(ArrayList<ArrayList<AsyncHttpRequestBo>> result) {
for (ArrayList<AsyncHttpRequestBo> httpRequestList : result) {
CallserverSubAsync callserverSubAsync = new CallserverSubAsync(context, this);
callserverSubAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, httpRequestList);
// ArrayList<AsyncHttpResponseBo> processResponseList = null;
// try {
// processResponseList = callserverSubAsync.get();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
}
listener.onAsyncTaskCompleted(responseList, listener);
progressDialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
progressDialog.dismiss();
super.onCancelled();
}
#Override
public void onAsyncTaskCompleted(ArrayList<AsyncHttpResponseBo> responseList, PlatwareResponseListener listener) {
if (listener instanceof CallServerAsync) {
processResponseList = responseList;
for (AsyncHttpResponseBo responseBo : processResponseList) {
this.responseList.add(responseBo);
}
}
}

Android AsyncTask Dialog fast close

My code:
private class selectBookInAutor extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
arr_book_title.clear();
arr_book_href.clear();
mProgressDialog = new ProgressDialog(_context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
StringBuilder sb = new StringBuilder();
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
Elements links = doc.select("li>a");
for (Element link : links) {
sb.append(link.text());
arr_book_title.add(link.text());
arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
}else if(seletedItems.contains(indexSelected)){
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
for (Object s : seletedItems){
String[] separated = selGroupParam.split(";");
String _idautor = separated[0].toString();
long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
new **saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));**
}
refreshList();
}
}).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog.dismiss();
}
}
private class saveBookInAutor extends AsyncTask<String, Void, String> {
String _idautor, _idbook;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(_context);
mProgressDialog2.setMessage("Save to file");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[1];
_idbook = params[2];
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
_html = doc.select("dd").outerHtml();
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
//String html = result;
**savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);**
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog2.dismiss();
}
}
public void refreshList() {
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
}
public void savePageToFile(String filename, String html) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
}
}
When you select a page and clicking "Ok" ProgressDialog mProgressDialog2 opens and displays just a 1 second. Because of this, I do not see the download Page or not.
How to make mProgressDialog2 displayed all the while to save the page as a file?
Thank you!
UPD
What i want is :
Start mProgressDialog.
After downloading the page disappears and AlertDialog comes with the question what to choose.
After choosing, mProgressDialog2 should be displayed as long as it downloads and saves the file in the webpage.
However mProgressDialog2 disappears in 1 second, and process of saving the file goes on in silence.
In your onPostExecute method, you unconditionally call
mProgressDialog2.dismiss();
This is closing the dialog immediately after it is displayed. That call should be moved to the handler code for each of the buttons. (i.e.the onClick method for the positive and negative buttons)
in onPostExecute(), compare Strings like
if(!result.equals(""))
and try once.
use equals() method for String comparisons.

Progress Dialog only shows up when the job is already done

I have a problem which I don't understand. I want to show a simple Progress Dialog in Android. So I created an AsyncTask and create the dialog in the constructor. I use the methods onPreExceution to initialise the dialog and the onPostExecute method I destory the dialog. So until now this looks total correct for me. But when I start the App on my Nexus 7 the dialog doesn't show up till the job is done. So it shows up for a half of a second at the end of the job... What am I doing wrong?
Thank you for your help ;)
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
public ParseHTMLCodeNew(Context context) {
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
UPDATE
This is my new AsyncTask:
public class ParseHTMLCodeNew extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private final OnCompleteTaskListener onCompleteTaskListener;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result){
onCompleteTaskListener.onComplete(result);
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
And i am calling it this way:
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
gData = data;
}
}).execute(url);
As i commented on your post, data has no value.
If you calling this code so:
String data = new ParseHTMLCodeNew(CommentActivity.this).execute(url).get();
Then you do not really see your dialogue because there is a blocking UI.
Method get() waits if necessary for the computation to complete, and then retrieves its result.
Call so:
new ParseHTMLCodeNew(CommentActivity.this).execute(url);
and the result of the work is handled directly in the AsyncTask.
If you need to transfer the data to the main thread, you should tell him that the task was completed.
Wat is the simple code, I just added OnCompleteTaskListener interface
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
private final OnCompleteTaskListener onCompleteTaskListener;
private ProgressDialog dialog;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
// einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
// your code here
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
sb.append(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
onCompleteTaskListener.onComplete(result);
}
}
And the example of a call
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
Toast.makeText(CommentActivity.this, data, Toast.LENGTH_LONG).show();
}
}).execute("your_url");
Be careful, this code can produce errors when you rotate your Phone.
When Activity destroyed but task is performed:
- progress dialog will close and will not open again
- local variable to dialog or context is incorrect.
If the operation is performed for a long time can make it through the of the services?
I've wrote a code that get data from online database and populate that data in lisview here is the part of my code hope that help !
class LoadMyData extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//Your code here
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// In my case use my adapter to display the data in a listview
adapter = new MyAdaper();
list.setAdapter(adapter);
}
});
}
}
Progress dialog should be shown from UI thread
runOnUiThread(new Runnable() {
public void run() {
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}});

Making an Asynchronous requests within a Android services

in my Service I am using http://loopj.com/android-async-http/
within the doInBackground() method of a service. Because it's asynchronous, the method finishes before the callbacks are called, and therefore onPostExecute is being called and shutting the service down... How can I avoid this?
public class LoginService extends AsyncTask<String, Void, LoginService.LoginStatus> {
private static String TAG = "x-LoginService";
private ProgressDialog progressDialog;
private AlertDialog dialog = null;
private final Context context;
public LoginService(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", context.getString(R.string.waitingLogin), true);
}
#Override
protected void onPostExecute(LoginStatus loginStatus) {
progressDialog.dismiss();
Log.d(TAG, "--STARTONPOSTEXECUTE");
String message;
LocalSettingsService settings = new LocalSettingsService(context);
if (loginStatus == LoginStatus.LOGGED_IN) {
settings.put("loggedIn", "true");
Intent intent = new Intent(context, FragmentTabs.class);
context.startActivity(intent);
//Intent intent = new Intent(context, SummaryPage.class);
//Intent intent = new Intent(context, FeedbackPage.class);
//Intent intent = new Intent(context, NavTab.class);
//context.startActivity(intent);
return;
} else if (loginStatus == LoginStatus.INVALID_CREDENTIALS) {
settings.put("loggedIn", "false");
message = context.getString(R.string.invalidCredentials);
} else {
settings.put("loggedIn", "false");
message = context.getString(R.string.serverError);
}
dialog = new AlertDialog.Builder(context)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(context.getString(R.string.errorTitle))
.setMessage(message)
.setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create();
dialog.show();
}
#Override
protected LoginStatus doInBackground(String... strings) {
String username = strings[0];
String password = strings[1];
doLogin();
return LoginStatus.LOGGED_IN;
}
private void doLogin() {
{
Log.d(TAG, "--STARTDOLOGIN");
RequestParams params = new RequestParams();
params.put("username", "un");
params.put("password", "pw");
ServicesRestClient.post("ajax/login", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(String s) {
Log.d(TAG, "--ONSUCCESS");
}
#Override
public void onFailure(Throwable throwable, String s) {
Log.d(TAG, "--ONFAILURE");
}
});
}
}
public void onPause() {
if (dialog != null) {
dialog.dismiss();
}
}
public static enum LoginStatus {
LOGGED_IN, INVALID_CREDENTIALS, SERVER_SIDE_ERROR
}
}
I think you this code too much complicated. In general you should somehow stay in doInBackground() unless you service ends, but not knowing the internals of what you use I can tell how to do it best. But since this library you use announces to be doing asynchronous networking, I'd not use another async task in first place

Categories

Resources