How to show the loading dialog - android

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

Related

Progress Dialog is not shown during execution of AsyncTask

I googled for hours and tried all answers of Stack Overflow but didn't solved my problem.
I made android program to download data in bytes which wroks perfectly. And for download working on background thread. I want to show a Progress Dialog(jus Spinning one). But I'm having really annoying problem. My download takes about 5 sec but my progress dialog is either not shown or just shown for last 1 sec.
Here's my code for AsyncTask.
public class ImageJSON extends AsyncTask<String, String, byte[]> {
private JSONObject jsonObject = new JSONObject();
private byte[] response;
private ProgressDialog pg;
private Context context;
public ImageJSON(Activity activity) {
pg = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pg.setMessage("Downloading, please wait.");
pg.show();
}
#Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
if (pg != null) {
pg.setProgress(Integer.parseInt(progress[0]));
}
}
protected void onPostExecute(byte[] result) {
if (pg.isShowing()) {
pg.dismiss();
}
}
#Override
protected byte[] doInBackground(String... params) {
HttpPost httpPost = new HttpPost("my file url....");
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
try {
jsonObject.put("imageId", params[0]);
StringEntity stringEntity = new StringEntity(jsonObject.toString());
httpPost.addHeader("Content_Type", "application/octet_stream");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
HttpEntity entity = httpResponse.getEntity();
if (entity!=null) {
response = EntityUtils.toByteArray(entity);
entity.consumeContent();
httpClient.getConnectionManager().shutdown();
}
} catch (JSONException|IOException e) {
e.printStackTrace();
}
return response;
}
And I called it from my activity using this code.
final ImageJSON imageTask = new ImageJSON(ReaderActivity.this);
byte[] response = imageTask.execute(imageId).get();
If anybody can help me, Thanks in advance.
You don't want to be using get() as it still freezes your UI thread thus denying the sense of using AsyncTask. You might want to implement onPostExecute in order to return your result properly.
try this -
public ImageJSON(Activity activity) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(ReaderActivity.this);
pg.setMessage("Downloading, please wait.");
pg.show();
}
you forgot to initilise your progressDialogue in onPreExecute method
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(pass_context_here);
pg.setMessage("Downloading, please wait.");
pg.show();
}
Change this
public ImageJSON(Context ctx) {
this.context = ctx;
}
Now in your onPreExecute() method use this
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(context);
pg.setMessage("Downloading, please wait.");
pg.show();
}
You'r initializing your ProgressDialog in ImageJSON class which block your UI thread means freezes it. So need to initialize it in onPreExecute() method with reference of context.

AsyncTask has stopped calling doInBackground

I have been using this code for the last few days and up until today it has been working perfectly, but for some reason the Async task has stopped calling the doInBackground method. I have attempted the solution suggested here Android SDK AsyncTask doInBackground not running (subclass) but I just get the same result. The onPreExecute method gets called but then I am just left with the loading dialog. Has anybody experienced anything similar to this. I have included a copy of my code. MyAsncTask is executed as follows;
new MyAsyncTask().execute(email, password);
private class MyAsyncTask extends AsyncTask<String, Void, JSONObject>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
Log.v(tag, "onPreExecute");
super.onPreExecute();
pDialog = new ProgressDialog(SignInPageActivity.this);
pDialog.setMessage("Logging in...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
Log.v(tag, "doInBackground");
CustomerFunctions userFunction = new CustomerFunctions();
if (params.length != 2)
return null;
JSONObject json = userFunction.loginUser(params[0], params[1]);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
Log.v(tag, "onPostExecute");
try {
if (json != null && json.getString(KEY_SUCCESS) != null) {
signInError.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("customer");
// Clear all previous data in database
CustomerFunctions userFunction = new CustomerFunctions();
userFunction.logoutCustomer(getApplicationContext());
databaseHandler.addUser(json.getString(KEY_UID), json_user.getString(KEY_FIRST_NAME), json_user.getString(KEY_LAST_NAME), json_user.getString(KEY_EMAIL), json_user.getString(KEY_CURRENT_STAMPS), json_user.getString(KEY_TOTAL_STAMPS), json_user.getString(KEY_REWARDS_AVAILABLE), json_user.getString(KEY_REWARDS_CLAIMED), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent main = new Intent(getApplicationContext(), MainActivity.class);
// Close all views before launching Dashboard
// dismiss the dialog once done
pDialog.dismiss();
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
// Close Registration Screen
finish();
}else{
// Error in login
signInError.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try extending like this
private class MyAsyncTask<Params, Void, JSONObject> extends AsyncTask<Params, Void, JSONObject>
and use #Override for doInBackground

onPostExecute() not executing in AsyncTask

I am trying to create an activity that allows a user to login by checking the username and password from a database, however after the creadentials are fetched successfully, the doInbackground doesnt stop executing.I not sure what i can do to make the onpostexecute to run. Here is the code
public class LoginActivity extends Activity{
public String username;
public String password;
public String userid;
JSONParser jParser = new JSONParser();
JSONObject json;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
context=getApplicationContext();
setContentView(R.layout.activity_login);
Button loginbutton=(Button) findViewById(R.id.loginbutton);
final EditText usernameText=(EditText) findViewById(R.id.usernameInput);
final EditText passwordText=(EditText) findViewById(R.id.passwordInput);
loginbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
username=usernameText.getText().toString();
password=passwordText.getText().toString();
if(username.trim().length()==0 || password.trim().length()==0){
AlertDialogManager diag=new AlertDialogManager();
diag.showAlertDialog(getApplicationContext(), "Fill Fields", "enter a username and password", false);
}else{
//send the username and password for verification
new Login().execute();
}
}
});
}
//http class starts here.
class Login extends AsyncTask<String, String, String> {
InputStream is = null;
JSONObject jObj = null;
ProgressDialog pDialog;
static final String url = "http://10.0.2.2/newptk/dalvik/auth.php";
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Authenticating...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.e("Auth", "working");
JSONArray document = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jParser.makeHttpRequest(url, "POST", params);
return null;
}
protected void onPostExecute() {
pDialog.dismiss();
SessionManager smg=new SessionManager(getApplicationContext());
int flag = 0;
try {
flag = json.getInt("success");
if(flag==1){
userid=json.getString("userid");
//set the session
smg.createLoginSession(username, userid);
//Login the user
Intent i = new Intent(getApplicationContext(), ReportFound.class);
startActivity(i);
finish();
}else{
AlertDialogManager diag=new AlertDialogManager();
diag.showAlertDialog(LoginActivity.this, "Login", "Incorrect Username/password", false);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}//end of http class
}
The first thing I see is that you are telling onPostExecute() to accept a String in your class header
class Login extends AsyncTask<String, String, String>
but aren't accepting anything or passing anything to it
protected void onPostExecute() {
if you don't want to pass it anything then change it to
class Login extends AsyncTask<Void, Void, Void>
and
protected void onPostExecute(Void result) {
...
}
#Override
protected void doInBackground(String... arg0) {
Notice this section in the Docs
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the
background computation.
Result, the type of the result of the
background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Change
protected void onPostExecute()
to
protected void onPostExecute(String result)
and you should be golden. Consider adding #Override tags in your code to prevent these subtle bugs in the future.

Cancel or dismiss android alert dialogue

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

how to a set progress bar till get a data from server using json? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Android AsyncTask Progress bar
Am using login process,during tat time am getting the data from server is delay.so i want set a progress bar for tat delay.how to set progress bar till get a response from server.any know the answer please help me.
private class LongOperation extends AsyncTask<String, Void, String>
{
protected void onPreExecute()
{
progressDialog = new ProgressDialog(activity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected String doInBackground(String... params)
{
try
{
//Getting data from server
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
Intent n = new Intent(firstactivity.this, secondactivity.class);
startActivity(n);
}
}
How to call this
ProgressDialog progressDialog;
LongOperation mytask = null;
mytask = new LongOperation();
mytask.execute();
Use AsyncTask in your code and put your code in doInBackground(....) process.
Show your progress dialog in onPreExecute and dismiss it in onPostExecute(...) .
Add an infinite progressbar view to your layout and make it invisible first.
Create an AyncTask to do the server communication.
In onPreExecute() make the progressbar visible.
In onPostExecute() hide the progressbar again.
You can use the onProcessupdate method of an AsyncTask
private class GetLogin extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show("Downloading...");
}
#Override
protected String doInBackground(String... params) {
for (String myUrl : params) {
try {
URL url = new URL(myUrl);
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("Accept", "application/xml");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
String str = new String(baf.toByteArray(), "UTF8");
return str;
} catch (MalformedURLException e) {
//error
} catch (IOException e) {
//error
}
}
return "All Done!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pd.setMessage("Downloading... (" + values[0] + "%)");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}

Categories

Resources