Making an Asynchronous requests within a Android services - android

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

Related

Android Retrofit : Wait for response

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();
}
}
});
}

AsyncTask not working inside ViewPager

I am having problem with AsyncTask class inside ViewPager's Fragment.
I have added code like below inside ViewPager's 3rd Fragment:
private View.OnClickListener finishClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
UserIdAsyncTask userIdAsyncTask = new UserIdAsyncTask( getActivity(), "URL", "Test", "Value" );
userIdAsyncTask.execute();
Her is my UserIdAsyncTask class:
private class UserIdAsyncTask extends AsyncTask<Void, Void, String> {
String url = "";
String oldpass = "";
String newpass = "";
private Context mContext = null;
private ProgressDialog dialog;
public UserIdAsyncTask( Context context, String url, String oldPass, String newPass ) {
this.mContext = context;
this.url = url;
this.oldpass = oldPass;
this.newpass = newPass;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(this.mContext, "", "Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String str = "";
try {
return str;
} catch (Exception e) {
Log.e(ThirdFrag.class.toString(), e.getMessage(), e);
}
return str;
}
#Override
protected void onPostExecute(String response) {
dialog.dismiss();
Intent i = new Intent(getActivity(), ABC.class);
startActivity(i);
getActivity().finish();
}
}
In the given code, onPreExecute() called but doInBackground() never called.
Any ideas anyone? I'm really struggling with this one.

How to read Alert Dialog in separate thread in android?

I have an AlertDialog builder in class. I am setting some message into it which comes from reading a file. Earlier as file text wasn't too large it use to load easily, now since the text has grown more it takes a time to load dialog and blocks UI. How can i run this in thread ?
Edited code :
public class Eula TaskCompleteListner{ {
static interface OnEulaAgreedTo {
void onEulaAgreedTo();
}
public static boolean show(final Activity activity,final Context context,final Boolean flag) {
final Preferences prefs = Preferences.getInstance();
Log.d(TAG, "insideEula");
if (!prefs.getEulaStatus(context)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
activity);
Log.d(TAG, "insideEulaLaunch");
builder.setTitle(R.string.eula_title);
builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.setEulaStatus(context, true);
if (activity instanceof OnEulaAgreedTo) {
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
});
builder.setNegativeButton(R.string.eula_refuse,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
refuse(activity);
}
});
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
MyAsync async= new MyAsync(this, activity) ;
async.excecute();
//builder.setMessage(readEula(activity)); //READING FILE AND SETTING HERE
//builder.create().show();
return false;
}
return true;
}
private static void refuse(Activity activity) {
activity.finish();
}
#Override
public boolean onComplete(String result) {
// TODO Auto-generated method stub
builder.setMessage(readEula(activity)); //READING FILE AND SETTING HERE
builder.create().show();
return false;
}
Async Task Class
public class MyAsync extends AsyncTask<Void, Void, String>{
public static final String ASSET_EULA = "EULA";
TaskCompleteListner taskCompleteListner;
Activity activity;
public interface TaskCompleteListner{
public boolean onComplete(String result);
}
public MyAsync(TaskCompleteListner taskCompleteListner,Activity activity) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}
#Override
protected String doInBackground(Void... params) {
String data=(String)readEula(activity);
return data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
taskCompleteListner.onComplete(result);
}
private static CharSequence readEula(Activity activity) { //READING FILE HERE
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
buffer.append(line).append('\n');
byte[] latin1 = buffer.toString().getBytes("ISO-8859-1");
return new String(latin1);
//return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
}
You can use AsyncTask class, where you read your data in doInBackground() return the CharSequence and do the dialog.show() in onPostExecute().
EDIT:
heres what you can do,
create a class
private static class MyAsyncClass extends AsyncTask<Void,Void,CharSequence > {
Activity activity;
ProgressDialog dialog
public MyAsyncClass(Activity activity){
this.activity = activity;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Reading data");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected CharSequence doInBackground(Void... params) {
return readEula(activity);
}
protected void onPostExecute(CharSequence data) {
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
final AlertDialog.Builder builder = new AlertDialog.Builder(
activity);
Log.d(TAG, "insideEulaLaunch");
builder.setTitle(R.string.eula_title);
builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.setEulaStatus(context, true);
if (activity instanceof OnEulaAgreedTo) {
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
});
builder.setNegativeButton(R.string.eula_refuse,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
refuse(activity);
}
});
builder.setMessage(data);
builder.create().show();
}
}
then call this class as,
if (!prefs.getEulaStatus(context)) {
MyAsyncClass myAsyncClass = new MyAsyncClass(activity);
myAsyncClass.execute();
}
Correction to your Edit:
in your Eula class,
change this,
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
MyAsync async= new MyAsync(this, activity) ;
async.excecute();
to this,
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
async.excecute();
in your Async class,
change your constructor to,
public MyAsync(Activity activity, TaskCompleteListner taskCompleteListner) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}
Use this Async Class to get the text
public class MyAsync extends AsyncTask<Void, Void, String>{
TaskCompleteListner taskCompleteListner;
Activity activity;
public interface TaskCompleteListner{
public boolean onComplete(String result);
}
public MyAsync(TaskCompleteListner taskCompleteListner,Activity activity) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}
#Override
protected String doInBackground(Void... params) {
String data=(String) readEula(activity);
return data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
taskCompleteListner.onComplete(result);
}
private static CharSequence readEula(Activity activity) { //READING FILE HERE
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
buffer.append(line).append('\n');
byte[] latin1 = buffer.toString().getBytes("ISO-8859-1");
return new String(latin1);
//return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
}
You can use this in your Eula class as follows:
if (!prefs.getEulaStatus(context)) {
MyAsync async= new MyAsync(activity,new TaskCompleteListner() {
#Override
public boolean onComplete(String result) {
//TODO show your alert dialog here. Result has the string needed
return false;
}
}) ;
}
Hope this helps.
If its just a dialog u need to show, you can use the Activity's following method:
public final void runOnUiThread (Runnable action)
AsyncTask would be a cleaner approach. However, this will save you the trouble of extra code if you are looking for a quick switch onto the main thread.
Async task will be the better approach.
1. Do your background operation (readEula(Activity activity)) in doInBackGround and
2. show dialog in onPostExecute method.
In another approach create thread and do your operation (readEula(act)) in it and use handler to communicate to this thread and show alert dialog in you activity only.

Calling static Async task from other fragment

I am trying to call Async task in some other activity from a fragment. I tried to call various way but none of it worked. I just want to know whats the best way to call static AsyncTask .Here is my Async task:
static class MyAsync extends AsyncTask<Void, Void, Void> {
Context context;
String username, password;
private MyAsync(Context context, String username, String password) {
this.context = context;
this.username = username;
this.password = password;
}
ProgressDialog dialog;
private String response;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "Connecting to Server","Getting Credentials"
, true);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
ContentDownload download = new ContentDownload();
response = download.loginApi(agentId, password);
if(response.contains("Success")){
if(SettingHelper.getFirstCall(context)){
ContentDownload.CallApi(context);
SettingHelper.setFirstCall(context, false);
}
if(SettingHelper.getFirstLaunch(context)){
ContentDownload load = new ContentDownload();
load.callItemApi(context);
load.callActionApi(context);
SettingHelper.setFirstLaunch(context, false);
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(response.contains("Success")){
context.startActivity(new Intent(context, AllActivity.class));
}else{
Toast.makeText(context, "Got back", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}}
I am trying to call it this way:
LoginActivity.new MyAsync(getActivity).execute();
but its giving error
It you want to use this class from your Fragment, give it public visibility, also a public constructor and then you can call it:
new LoginActivity.MyAsync(getActivity())

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.

Categories

Resources