I am creating / showing a loading in my android view with the following function
public void showDialogue(String Message, String Title){
builder = new AlertDialog.Builder(this);
progress = new ProgressBar(this);
builder.setMessage(Message);
builder.setView(progress);
builder.create().show();
}
I am calling this function as an asyn tasklike
private class SetParm extends AsyncTask<String, Integer, String> {
Integer myid;
Integer myFlag;
Integer removeId;
#Override
protected String doInBackground(String... sUrl) {
try {
SharedPreferences mPrefs = getSharedPreferences("prefs",0);
String restoredText = mPrefs.getString("access_token", "");
String path = "http://www.sitename.com/app/setFlag.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("access_token", restoredText);
json.put("id", myid);
json.put("flag", myFlag);
Log.i("jason Object", json.toString());
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
Log.v("TAGG",a);
String passedStringValue = jsono.getString("result");
if(passedStringValue.equals("1")){
flags=1;
//Log.v("TAGG", "Success");
SharedPreferences mPrefss = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = mPrefss.edit();
editor.putString("access_token", jsono.getString("access_token"));
editor.commit();
}
else {
flags=0;
//Log.v("TAGG", "Failed !");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
showDialogue("Regestring Your Devide... Please wait.", "Regestring Devide");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
builder.cancel();
if(flags.equals(1)){
TableLayout mTable = (TableLayout)findViewById(R.id.tableLayout_1);
mTable.removeView(findViewById(4500+removeId));
mTable.removeView(findViewById(6500+removeId));
int count = mTable.getChildCount();
if(count<=0){
lists="";
total="0";
LogIN loginUsers1 = new LogIN();
loginUsers1.execute("");
}
}
else {
TextView text = (TextView) findViewById(R.id.status_msg);
text.setText("Error while processing requests. Please try again.");
}
super.onPostExecute(result);
}
}
Calling the alert dialogue from onPreExecute() function.
Now I need to remove the loading once the webservice request has been completed
So I wrote builder.cancel(); in onPostExecute but its not working
Any idea ?
Thanks in advance
Instead of the normal dialog, you can use progress dialog as shown below:
private ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog= new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading ....");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
}
Customization of progress Bar.....
//Pre Execute method
#Override
protected void onPreExecute()
{
super.onPreExecute();
ProgressDialog pDialog = new ProgressDialog(Activity.this);
pDialog= ProgressDialog.show(.this, "","Loading. Please wait...", true);
pDialog.setContentView(R.layout.progressbar);
pDialog.setCancelable(false);
}
////////////////////////////////////////////////////////////////////////////////////////
Progress bar xml layout
that is progressbar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="150dip"
android:layout_height="150dip"
android:background="#drawable/progressbar_shap"
android:layout_gravity="center">
<TextView android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Please Wait..."
android:textStyle="bold"
/>
<ProgressBar
android:indeterminateDrawable="#drawable/my_progress_indetermine"
android:layout_height="60dp"
android:layout_width="60dp"
android:layout_centerInParent="true"
></ProgressBar>
</RelativeLayout>
////////////////////////////////////////////////////////////////////////
After that
my_progressbar_indertimine.xml
<?xml version="1.0" encoding="utf-8"?>
<animated-rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#drawable/please_wait"
android:pivotX="50%"
android:pivotY="50%" />
//Post execute method , which will dismiss progress bar.
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
}
"please_wait" progress bar image , it will show white , when you will use below link
,but you can save it, Right click on browser page and use "save as"
http://i.stack.imgur.com/hnY8r.png
Try Like this
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity.this);
pDialog.setMessage("Loading Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
And in onPostExecute do like this
protected void onPostExecute(String result) {
super.onPostExecute(toString());
// dismiss the dialog after loading
pDialog.dismiss();
}
You can use Dialog instead of AlertDialog and call dialog.dismiss() in onPostExecute()
EDIT: Please do not consider this answer as solution. Because I assumed that ramesh was using AlertDialog.Builder, and answered wrong. As with Dialog we have more options to customize, I suggested it.
Try This in your onPostExecute.....
#Override
protected void onPostExecute(String result) {
try{
builder.dismiss();
}
catch(Exception e){
}
if(flags.equals(1)){
TableLayout mTable = (TableLayout)findViewById(R.id.tableLayout_1);
mTable.removeView(findViewById(4500+removeId));
mTable.removeView(findViewById(6500+removeId));
int count = mTable.getChildCount();
if(count<=0){
lists="";
total="0";
LogIN loginUsers1 = new LogIN();
loginUsers1.execute("");
}
}
else {
TextView text = (TextView) findViewById(R.id.status_msg);
text.setText("Error while processing requests. Please try again.");
}
}
Try this code for async task and progress dialog,
public class MyTask extends AsyncTask<Void, Integer, Void> {
public MyTask(Activity activity, int id) {
this.activity = activity;
context = activity;
}
/** progress dialog to show user that the backup is processing. */
private ProgressDialog progressDialog;
/** application context. */
private Activity activity;
private Context context;
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(context, "", "Loading...");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
}
}
Related
I am trying to make login view.
I' d like to start a new AsyncTask that performs the REST call to the server and shows a progress bar. I need that the UI main thread wouldn't block and it must show a toast with message (like success or fail) depending on what the AsyncTask returns .
Here the code:
SetupActivity (main thread):
//Get reference SignUp Button
Button signupButton = (Button)myDialog.findViewById(R.id.button_signup_OK);
signupButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get all the textfield content from the form
name=((EditText)myDialog.findViewById(R.id.nameEditText)).getText();
surname=((EditText)myDialog.findViewById(R.id.surnameEditText)).getText();
email=((EditText)myDialog.findViewById(R.id.emailEditText)).getText();
password=((EditText)myDialog.findViewById(R.id.passwordEditText)).getText();
password_Retyped=((EditText)myDialog.findViewById(R.id.passwordRepEditText)).getText();
//Get hash from password
hashPassword=DigestMd5.md5(password);
hashPasswordRep=DigestMd5.md5(password_Retyped);
//Check if the fields are null
if(name.toString().equals("")){
((EditText) myDialog.findViewById(R.id.nameEditText)).setError(getString(R.string.mandatoryField));
}
if(surname.toString().equals("")){
((EditText) myDialog.findViewById(R.id.surnameEditText)).setError(getString(R.string.mandatoryField));
}
if(email.toString().equals("") ){
((EditText) myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.mandatoryField));
}else{
if(!new EmailValidator().validate(email.toString())){
((EditText)myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.emailWrong));
}
}
if(password.toString().equals("")){
((EditText) myDialog.findViewById(R.id.passwordEditText)).setError(getString(R.string.mandatoryField));
}
if(password_Retyped.toString().equals("")){
((EditText) myDialog.findViewById(R.id.passwordRepEditText)).setError(getString(R.string.mandatoryField));
}
//Check match password
if(!hashPassword.equals(hashPasswordRep)){
((EditText)myDialog.findViewById(R.id.passwordEditText)).setError(getString(R.string.passwordNotMatching));
((EditText)myDialog.findViewById(R.id.passwordRepEditText)).setError(getString(R.string.passwordNotMatching));
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
//Start AsyncTask
new loadingBar().execute().get();
Boolean resultOK = ackJSON.has("result");
if(resultOK){
//close dialog
myDialog.dismiss();
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_success,(ViewGroup) findViewById(R.id.custom_toast_layout_id));
Toast toastOK = new Toast(getApplicationContext());
toastOK.setDuration(Toast.LENGTH_LONG);
toastOK.setView(layout);
toastOK.show();
}else{
//Feedback both using Toasts and textedit
((EditText) myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.userAlreadyIn));
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_erroruser,(ViewGroup) findViewById(R.id.custom_toast_no_user));
Toast toastNoUser = new Toast(getApplicationContext());
toastNoUser.setDuration(Toast.LENGTH_SHORT);
toastNoUser.setGravity(Gravity.TOP,0,50);
toastNoUser.setView(layout);
toastNoUser.show();
}
} catch (IOException e) {
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_errorconnection,(ViewGroup) findViewById(R.id.custom_toast_no_noConn));
Toast toastNoConn = new Toast(getApplicationContext());
toastNoConn.setDuration(Toast.LENGTH_SHORT);
toastNoConn.setGravity(Gravity.TOP,0,50);
toastNoConn.setView(layout);
toastNoConn.show();
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
}
class loadingBar extends AsyncTask<Void,Integer,JSONObject>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setProgress(0);
progress.show();
}
#Override
protected JSONObject doInBackground(Void... arg0)
{
ackJSON = null;
try
{
for(int i=0;i<2;i++)
{
publishProgress(new Integer[]{i*10});
Thread.sleep(1200);
}
String ack=HTTPRest.putNewUser(name.toString(),surname.toString(),email.toString(),hashPassword);
ackJSON=new JSONObject(ack);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ackJSON;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progress.setProgress(values[0].intValue());
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progress.dismiss();
ackJSON=result;
}
}
Please let me know for any error in code
Thank you
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
//checkLogin(email, password);
new AttemptLogin().execute();
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
class AttemptLogin extends AsyncTask<String, String, String>{
/** * Before starting background thread Show Progress Dialog * */
boolean failure = false;
#Override protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(AppConfig.URL_LOGIN, "POST", params);
// checking log for json response
//devraj......................
Log.d("Login attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1){
session.setLogin(true);
Log.d("Successfully Login!", json.toString());
Intent intent = new Intent(LoginActivity.this,Secondpage.class);
startActivity(intent);
return json.getString(TAG_MESSAGE);
}
else{
return json.getString(TAG_MESSAGE);
}
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
/** * Once the background process is done we need to Dismiss the progress dialog asap * **/
protected void onPostExecute(String message)
{
pDialog.dismiss();
if (message != null){
Toast.makeText(First.this, message, Toast.LENGTH_LONG).show();
}
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
All is correct but you will change for this code
if(name.toString().isEmpty()){
}
because your code is some time problem when you not enter any value then not check your condition. Your code will check only black space.
You can show Toast in your onPostExecute() method
The lifecycle of Asynktask is runs like this
onPreExecute() -> runs first
doInBackground() -> After onPreExecute
and
`onPostExecute()` -> After doInBackground
So you can update UI or show Toast in onPostExecute()
You can do your work inside onPostExecute method of AsyncTask
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progress.dismiss();
ackJSON=result;
//do your work here show toast or move to next activity
}
progress.setCancelable(false);
I am trying to create a dialog when loading Httprequest. But it load during the i click to intent from last Activity, but not the start of this Activity.
And the dialog just shown in 0.00001sec then dismiss.
Am i implement it wrongly?
Here is my codes
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpPostHandler2 handler = new HttpPostHandler2();
String URL ="http://xxxxxx";
handler.execute(URL);
}
public class HttpPostHandler2 extends AsyncTask<String, Void, String> {
private String resultJSONString = null;
private ProgressDialog pDialog;
public String getResultJSONString() {
return resultJSONString;
}
public void setResultJSONString(String resultJSONString) {
this.resultJSONString = resultJSONString;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
AuthScope.ANY_PORT), new UsernamePasswordCredentials("core",
"core1234"));
String responseContent = "";
HttpClient httpClient = new DefaultHttpClient();
((AbstractHttpClient) httpClient).setCredentialsProvider(credProvider);
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse response = null;
try {
// Execute HTTP Post Request
response = httpClient.execute(httpPost);
responseContent = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
setResultJSONString(responseContent);
// return new JSONObject(responseContent);
return responseContent;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
resultJSONString = result;
}
}
Make sure that the work of HttpPostHandler2 is long enough to display the pDialog. If it not, it will disappear really soon.
However, you cannot display GUI in onCreate. To display the dialog, you should move them to onStart:
#Override
public void onCreate(Bundle savedInstanceState) {//GUI not ready: nothing is shown
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpPostHandler2 handler = new HttpPostHandler2();
}
#Override
protected void onStart () {//GUI is ready
String URL ="http://xxxxxx";
handler.execute(URL);
}
See comment for more information.
I am getting a JSON response from a URL and convert it into a string. I want to parse this string to get some values from the response. But when the parsing takes place the application shows a blank screen(black screen) until the response is parsed. I wanted to show a ProgressDialog which shows how much data is to be downloaded so that the app does not show that blank screen. I tried showing a ProgressDialog but it is shown before the parsing and after it is done. The in between time still shows the blank screen.
Here is my code:-
String registerContet = "myUrl";
String items;
try
{
items = new FetchItems().execute(registerContet).get();
pDialog = new ProgressDialog(this).show(Home.this, "Fetching news items", "Please wait..");
JSONArray jObject = new JSONArray(items);
for (int i = 0; i < jObject.length(); i++)
{
JSONObject menuObject = jObject.getJSONObject(i);
String title= menuObject.getString("Title");
String description= menuObject.getString("BodyText");
String thumbnail= menuObject.getString("ThumbnailPath");
String newsUrl = menuObject.getString("Url");
String body = menuObject.getString("Body");
String newsBigImage = menuObject.getString("ImageBlobUrls");
map = new HashMap<String,String>();
map.put(SOURCETITLE, title);
map.put(TITLE, description);
map.put(THUMBNAILPATH, thumbnail);
map.put(BODY, body);
map.put(URL, newsUrl);
map.put(IMAGEBLOBURLS,newsBImage);
myNList.add(map);
}
itemsAdapter = new LazyAdapter(Home.this, myNList);
if(pDialog!=null && pDialog.isShowing())
{
pDialog.dismiss();
}
nList.setAdapter(itemsAdapter);
nList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int position, long arg3)
{
// TODO Auto-generated method stub
myDialog = new ProgressDialog(Home.this).show(Home.this, "Fetching news..", "Just a moment");
HashMap<String, String> myMap = myNList.get(position);
Intent nIntent = new Intent(Home.this,NDetails.class);
newsIntent.putExtra("NItems", myMap);
startActivity(nIntent);
}
});
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FetchItems.java is
private class FetchItems extends AsyncTask<String, String, String> {
// TODO Auto-generated method stub
ProgressDialog myDialog;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpResponse response = null;
String resultString = "";
String myResponseBody = "";
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpGet request = new HttpGet(params[0]);
try {
response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
myResponseBody = convertToString(inputStream);
}
}
} catch (Exception e) {
}
return myResponseBody;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
/*
* if(myDialog.isShowing()) { myDialog.dismiss(); }
*/
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*
* myDialog = new ProgressDialog(Home.this);
* myDialog.setMessage("Loading"); myDialog.show();
*/
}
}
Can anyone tell me how can I resolve this.
Thanks
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
Creating dialog in activity:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Converting..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Show dialog in onPreExecute()
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
Dismiss dialog in onPostExecute()
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
Use this code with in onPreExecute method,
private ProgressDialog dialog;
dialog = new ProgressDialog(this);
dialog.setMessage("Please Wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
easy and simple code for percentage in dialog of progress dialog
> protected void onPreExecute() {
dialog = new ProgressDialog(UploadActivity.this);
dialog.setMessage("Loading, please wait.. ");
dialog.show();
dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setMessage("Loading, please wait.. "+String.valueOf(progress[0])+"%");
}
I am using an AsyncTask to download some big amount of data from a server my AsyncTask work fine so i added a progress bar to make everything beautiful but problem is when its running progress bar get freeze half way down, and i use progress dialog that also the same its freeze half way down,
private class downloadChannelsfromserver extends
AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... url) {
String data = "";
try {
// Fetching the data from web service
data = getLinksfromServer(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog= ProgressDialog.show(Settings.this, "Synchronicing","Synchronicing", true);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject json;
try {
json = new JSONObject(result);
db.deleteAll();
final JSONArray jsonArray = json.getJSONArray("XXXX");
for (int i = 0; i < jsonArray.length(); i++) {
///use for insert datainto database
}
finish();
progressDialog.dismiss();
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("settings", "", e);
progressDialog.dismiss();
}
}
can and someone tell me why this happen, Pls
Follow this code
private ProgressDialog pdialog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
if(pdialog ==null){
//display progress dialog like this
pdialog = new ProgressDialog(context);
pdialog.setCancelable(false);
pdialog.setMessage("Please Wait...");
pdialog.show();
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//dismiss progress dialog like this
if(pdialog!=null){
pdialog.dismiss();
pdialog = null;
}
}
Reason for progress bar get stuck was my JSON decoding since onPostExecute belongs to UI thread it take several time to decode the json results. so it will freeze the UI until JSON decode so move the decoding part to doInBackground will solve the UI freeze issue since doInBackground belongs to background thread
Please edit your code like this:
private class downloadChannelsfromserver extends
AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
public downloadChannelsfromserver()
{
progressDialog = new ProgressDialog(Settings.this);
progressDialog.setTitle("Synchronicing ...");
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
#Override
protected String doInBackground(String... url) {
String data = "";
try {
// Fetching the data from web service
data = getLinksfromServer(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
//super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject json;
try {
json = new JSONObject(result);
db.deleteAll();
final JSONArray jsonArray = json.getJSONArray("XXXX");
for (int i = 0; i < jsonArray.length(); i++) {
///use for insert datainto database
}
finish();
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("settings", "", e);
}
finally
{
progressDialog.dismiss();
}
}
I hope this helps.
Just Use This Code:
runOnUiThread(object : Runnable {
override fun run() {
pausingDialog =
SweetAlertDialog(this#History_Activity, SweetAlertDialog.PROGRESS_TYPE)
pausingDialog!!.titleText = "Please wait...."
pausingDialog!!.setCancelable(false)
pausingDialog!!.show()
}
})
runOnUiThread(object : Runnable {
override fun run() {
}
})
I try use below code to load an URL.
URL url = new URL(urlstr);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(10000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
InputStream is = connection.getInputStream(); //spend lots of time
Because the line InputStream is = connection.getInputStream(); will spend some time.
So I want to show a loading dialog while it loading.
I can I do it?
In AActivity, below code to call BActivity.
Intent intent = new Intent(AActivity.this, BActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window w = MyGroup.group.getLocalActivityManager().startActivity("BActivity", intent);
View view = w.getDecorView();
MyGroup.group.setContentView(view);
And BActivity is load URL and extract information.
The load code is in onCreate().
I try the answer code, the error Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#2afe9488 is not valid; is your activity running? shows.
You can achieve with the aysntask showing progress dialog as follows
In Oncreate :
new GetTask(this).execute();//taken object for asyntask class.
class GetTask extends AsyncTask<Object, Void, String> {
{
ProgressDialog progressDialog;
void GetTask(Context cntxt)
{
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(cntxt); //taking object for progress dialog
mDialog.setMessage("Please wait...");
mDialog.show(); //Displaying progressDialog
}
#Override
protected String doInBackground(Object... params) {
//do the background process
return ""; you can return string value
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (mDialog != null) {
mDialog.dismiss();//close the progress Dialog
}
}
}
You want a ProgressDialog. Refer to this link
use a constructor in DownloadWebPageTask to initialize the context and use that context in dialog.
or use yourclass.this in
dialog = new ProgressDialog(yourclass.this);
Progress dialog
private ProgressDialog dialog;
public void showProgress () {
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Please wait");
dialog.show();
}
Use asynchronous task for downloding...
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
//Do your downloading task
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
Call progress dialog before executing download task
showProgress();
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.url.com" });