I am trying to use a AlertDialog in Android which will notify the users that they are runing in offline mode after checking the internet connection.
I have used the following codes:
protected Void doInBackground(Void... params) {
if (this.isOnline()) {
new GetJson().execute();
} else {
AlertDialog.Builder builder1 = new AlertDialog.Builder(homeFragment);
builder1.setMessage("INTERNET CONNECTION NOT AVAILABLE. Now you are viewing the news in Offline Mode.");
builder1.setCancelable(true);
AlertDialog alert1 = builder1.create();
alert1.show();
try {
saveFile = new SaveIntoFile(fileName);
jsonStr = saveFile.read();
// Log.d(TAG,"offline data reading from a file");
if (!jsonStr.equals(null))
new GetDatas().execute();
else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
But I am getting the error on adding the codes for AlertDialog. The app works fine without the codes for AlertDialog.
What can be the mistakes with this code and how can i correct it to work well??
doInBackground() runs on a separate thread, other than the main thread. You can use UI elements only on main thread. Try using runOnUiThread() method inside doInBackground() to show the dialog.
here AlertDialog will not work, you can use
System.out.println("some text");
if you are using alert just for testing purpose.
otherwise you have to set into a parameter and what ever text you want to put in alertbox and just use it in main thread.
if you have any confusion please let me know .
In Android you can do UI operations only in main thread. So you can show dialog in onPostExecute method. Example:
class anyClassName extends AsyncTask<String,String,String>{
/* uses worker thread */
protected String doInBackground(Void... params) {
if (this.isOnline()) {
new GetJson().execute();
} else { return null }
// ... rest of your code
return ""
}
/* uses main thread*/
protected void onPostExecute(String result){
if(result == null ){
AlertDialog.Builder builder1 = new AlertDialog.Builder(homeFragment);
builder1.setMessage("INTERNET CONNECTION NOT AVAILABLE. Now you are viewing the news in Offline Mode.");
builder1.setCancelable(true);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
}
class myAsync extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
if(yourWorkIsDone){
return new String("done");
}else{
return new String("Error message");
}
//BUT, if you'd like to check and update user on the error and keep trying then this way
// use just one of these two examples
if(yourWorkIsDone){
// definately is done but hey it depends on you
publishProgress(new String("done"));
}else{
// this is when you have error and wona let the user know about and keep trying to hit it right
publishProgress(new String("error message"));
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// here your task is done
// you can put myAlertDialogToShow(Context context,String message) depending on ur choice
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
// here your task is running but you are just informing user, runs on the ui..
// you can put myAlertDialogToShow(Context context,String message) depending on ur choice
}
}
void myAlertDialogToShow(Context context,String message){
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage(message);
builder1.setCancelable(true);
AlertDialog alert1 = builder1.create();
alert1.show();
}
ayt..check for silly errors and spellings.. im tired
Related
what i have is two asynctask each one call a function to parse some data ... and i want the asynctask starts after asynctasknew finish how can i do this??? here is my code ..
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AsyncCallWS task = new AsyncCallWS();
try{
Intent newintent = getIntent();
mixlist=newintent.getStringArrayListExtra("listmix");
Log.e("listmix",mixlist+"");
for(int i=0;i<=mixlist.size();i++){
if(i==mixlist.size()){
Log.d("states","finished");
Item_Name="0";
Item_Price="0";
Item_Quantity="0";
Total_Price="0";
Customer_Name=name.getText().toString();
Log.e("customer_name",Customer_Name);
Customer_Number=mobile.getText().toString();
Customer_Address=addressnew.getText().toString();
//Call execute
task.execute();
}
else{
Item_Name=mixlist.get(i);
i++;
Item_Price=mixlist.get(i);
i++;
Item_Quantity=mixlist.get(i);
i++;
Total_Price=mixlist.get(i);
Customer_Name="0";
Customer_Number="0";
Customer_Address="0";
// AsyncCallWSnew tasknew = new AsyncCallWSnew();
//Call execute
AsyncCallWSnew tasknew = new AsyncCallWSnew();
tasknew.execute();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
//Make Progress Bar invisible
Toast.makeText(getApplicationContext(), "order has been sent + item price", Toast.LENGTH_LONG).show();
Intent intObj = new Intent(PersonalInfo.this,MainActivity.class);
startActivity(intObj);
//Error status is false
}
//Make Progress Bar visible
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
loginStatus = WebService.invokeLoginWS(Item_Name,Item_Price,Item_Quantity, Total_Price, Customer_Name,
Customer_Number, Customer_Address,"InsertData");
return null;
}
}
private class AsyncCallWSnew extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
//Make Progress Bar invisible
Toast.makeText(getApplicationContext(), "order has been sent", Toast.LENGTH_LONG).show();
Intent intObj = new Intent(PersonalInfo.this,MainActivity.class);
startActivity(intObj);
//Error status is false
}
//Make Progress Bar visible
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
loginStatus = WebService.invokeLoginWS(Item_Name,Item_Price,Item_Quantity, Total_Price, Customer_Name,
Customer_Number, Customer_Address,"InsertData");
return null;
}
}
}
when i make a debug my code works just fine .. but in normal run .. it doesn't can any help me?
There are basically two possibilities:
Simply start the next AsyncTask from onPostExecute() of the previous one
Use AsyncTask.executeOnExecutor() with SerialExecutor and start all of them in a row.
Hi You can use AsyncTask executeonExecutor method to start the async task. But it will require minimum API version 11. Kindly refer the following code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new YourFirstTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params...);
new YourSecondTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params...);
}else{
new YourFirstTask().execute(params...);
new YourSecondTask().execute(params...);
}
For Lower version you can call directly. automatically system will process one by one.
I'm trying to show an AlertDialog in my AsyncTask on onCancelled. My task is stopping properly, but the dialog isn't appearing. Here's my code below... Need help. Thanks...
public class getWebPage extends AsyncTask<String, Integer, String> {
protected void onPreExecute(String f) {
// TODO Setting up variables
f = "f";
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Looper.prepare();
DefaultHttpClient urlClient = new DefaultHttpClient();
HttpGet getHtml = new HttpGet(PAGE_URL);
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
String htmlPage = urlClient.execute(getHtml, resHandler);
Log.d("Html Page", htmlPage);
confessionsPage = new File(getApplicationContext().getFilesDir(), "ConfessionsPage.html");
if (!confessionsPage.exists()) {
confessionsPage.createNewFile();
}
writer = new PrintWriter(confessionsPage, "UTF-8");
writer.print(htmlPage.replace("<!--", "").replace("-->", ""));
writer.flush();
writer.close();
Document doc = Jsoup.parse(confessionsPage, "UTF-8", "http://www.facebook.com/");
if (doc.title().contains("Welcome to Facebook")) {
aDialog = new AlertDialog.Builder(OpeningActivity.this).create();
aDialog.setTitle("Restricted Access");
aDialog.setMessage("Looks like your Confessions Page only allows login access. You may be logged in right now, but the app" +
" can't. Tell your page admin to allow non-logged in access for your confessions page.");
aDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
aDialog.dismiss();
}
});
getWebPage.this.cancel(true);
}
and here is my on cancelled method:
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
aDialog.show();
}
Try move everything from the doInBackground to the onCancelled.
So this will be your onCancelled:
AlertDialog aDialog = new AlertDialog.Builder(OpeningActivity.this).create();
aDialog.setTitle("Restricted Access");
aDialog.setMessage("Looks like your Confessions Page only allows login access. You may be logged in right now, but the app" +
" can't. Tell your page admin to allow non-logged in access for your confessions page.");
aDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
aDialog.dismiss();
}
});
aDialog.show();
And remove everything from the doInBackground.
Alternatively you can put this into your AsyncTask's onPostExecute too and change the result type of the task to Boolean. in the onPostExecute check the result. If it's false and you need to display this error. display it from there.
Note that onPostExecute is executed by the UI thread so you don't need the runOnUiThread stuff.
In the first run of my app, i have to copy database file to data folder. it takes about 10 sec and in this period of time user sees a black screen. I want to use AsynTask technique to show a progressbar. but it doesnt work an i see that progressbar after black screen goes away...
with this code i call copy database class and also i call AsynTsk process...
new asyn().execute();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
// throw new Error("Unable to create database");
}
and this is my AsynTask code:
public class asyn extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
//loading toast
//final DataBaseHelper myDbHelper = new DataBaseHelper(this);
String firstload2 = myDbHelper.getfirstload();
if(firstload2.matches("1")) {
dialog=new ProgressDialog(DictionaryActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
myDbHelper.changefirstload();
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// perform desired task in this doInBackground Block.
for(int i=0;i<20;i++)
{
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "";
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.incrementProgressBy(5);
}
#Override
protected void onPostExecute(String result)
{
dialog.dismiss();
AlertDialog.Builder a=new Builder(DictionaryActivity.this);
a.setMessage("Successfully Done");
a.setTitle("Try");
a.setPositiveButton("OK",null);
a.show();
}
}
where is my fault? how i can fix that?
myDbHelper.changefirstload(); should be within the doInBackground() method. onPreExecute() executes on the UI thread.
In terms of a progress bar, that's a bit difficult here. Personally, I'd do an indeterminate progress bar (just a spinning icon or something while it loads). If you want to have a % bar, though, you will need to break up the method into multiple methods, then update your progress in between them.
I have an inner class that downloads some images from the server. The problem is that the ProgressDialog does not dismiss() onPostExecute() method and don't understand why.
I understand that the progress dialog should be shown onPreExecute() method, and the after the code from the doInBackground() finished , in the onPostExecute() method the dialog should be dismiss. Do you have any idea what i am doing wrong here? Thank you.
/**
* Download images from server
*/
public class DownloadAsyncTask extends AsyncTask<Void, Integer, Void> {
private ProgressDialog mDialog;
// execution of result of Long time consuming operation
protected void onPostExecute(Void result) {
// progressDialog.show();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
// Things to be done before execution of long running operation.
protected void onPreExecute() {
mDialog = ProgressDialog
.show(ImagesActivity.this, getString(R.string.pleasewait),
getString(R.string.loading));
}
// perform long running operation operation
protected Void doInBackground(Void... params) {
System.out.println("doInBackground loading.." + id);
String tempPath = FileUtils.createTempFile(id);
for (int i = 0; i < imagePaths.size(); i++) {
imagePaths.get(i).trim();
try {
Bitmap imgTemp;
imgTemp = FileUtils.downloadBitmapFromURL(id,
imagePaths.get(i), tempPath);
System.out.println("imgTemp: " + imgTemp);
if (imgTemp != null) {
// save image on sdcard.
// compress it for performance
Bitmap img = Bitmap.createScaledBitmap(imgTemp, 90, 80,
true);
imgTemp.recycle();
FileUtils.saveDataToFile(img, tempPath,
imagePaths.get(i));
} else {
continue;
}
} catch (IOException e) {
e.printStackTrace();
mDialog.dismiss();
}
}
Looper.prepare();
mDialog.dismiss();
return null;
}
/*
* Things to be done while execution of long running operation is in
* progress.
*/
protected void onProgressUpdate(Integer... values) {
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
actually what you are trying to do is to access the UI Thread from another thread and that is not possible , in your case you are using AsyncTask class enables proper and easy use of the UI thread without having to manipulate threads and/or handlers. use onPostExecute(Result) to access the UI Thread.
so this should work
protected void onPostExecute(Void result) {
progressDialog.show();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
I've struggled with this same problem for quite a while. Here is how I got it solved, take a look at this part of the documentation:
A dialog is always created and displayed as a part of an Activity. You
should normally create dialogs from within your Activity's
onCreateDialog(int) callback method. When you use this callback, the
Android system automatically manages the state of each dialog and
hooks them to the Activity, effectively making it the "owner" of each
dialog
Note: If you decide to create a dialog outside of the onCreateDialog()
method, it will not be attached to an Activity. You can, however,
attach it to an Activity with setOwnerActivity(Activity).
from: http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
This is an example of what you have to set on your activity:
#Override
protected void onPrepareDialog(int id, Dialog dialog)
{
//This doesn't do anything
if (id == DIALOG_PROGRESS_ID) {
((ProgressDialog)dialog).setIndeterminate(true);
}
super.onPrepareDialog(id, dialog);
}
#Override
protected Dialog onCreateDialog(int id)
{
if (id == DIALOG_PROGRESS_ID) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading");
dialog.setCancelable(false);
dialog.setIndeterminate(true);
return dialog;
}
return null;
}
You can then call
myActivity.showDialog(myActivity.DIALOG_PROGRESS_ID), myActivity.dismissDialog(myActivity.DIALOG_PROGRESS_ID) from any where as long as you have a reference to your activity instance.
Use a handler and onPostExecute() send the handler msg to dismiss the progress dialog.
You can get help from this link ProgressDialog dismissal in android
Your code is working fine but can you check that control are reaching in Post onPostExecute() method I have tried as
package com.alarm.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class AlarmManagerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up main content view
setContentView(R.layout.main);
new DownloadAsyncTask().execute();
}
/**
* Download images from server
*/
public class DownloadAsyncTask extends AsyncTask<Void, Integer, Void> {
private ProgressDialog mDialog;
// execution of result of Long time consuming operation
#Override
protected void onPostExecute(Void result) {
// progressDialog.show();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
// Things to be done before execution of long running operation.
#Override
protected void onPreExecute() {
mDialog = ProgressDialog.show(AlarmManagerActivity.this, "Hello", "Test");
}
// perform long running operation operation
#Override
protected Void doInBackground(Void... params) {
//System.out.println("doInBackground loading.." + id);
/* String tempPath = FileUtils.createTempFile(id);
for (int i = 0; i < imagePaths.size(); i++) {
imagePaths.get(i).trim();
try {
Bitmap imgTemp;
imgTemp = FileUtils.downloadBitmapFromURL(id, imagePaths.get(i), tempPath);
System.out.println("imgTemp: " + imgTemp);
if (imgTemp != null) {
// save image on sdcard.
// compress it for performance
Bitmap img = Bitmap.createScaledBitmap(imgTemp, 90, 80, true);
imgTemp.recycle();
FileUtils.saveDataToFile(img, tempPath, imagePaths.get(i));
}
else {
continue;
}
}
catch (IOException e) {
e.printStackTrace();
mDialog.dismiss();
}
}
Looper.prepare();
mDialog.dismiss();*/
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*
* Things to be done while execution of long running operation is in
* progress.
*/
#Override
protected void onProgressUpdate(Integer... values) {
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
}
I think problem in doInbackground() method. I have simply run thread for sleep 5 sec and after control reaches in post() method and dissmiss progress dialog.
progressDialog = ProgressDialog.show(GetResponse.this, "", "Loading...");
new Thread()
{
public void run()
{
try
{
// inside i have written code for making connection to the server using SSL connection.
}catch (Exception e)
{
progressDialog.dismiss();
exception(e.getMessage())
}.start();
}
private void exception(String msg)
{
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
this.finish();
Intent i = new Intent(getBaseContext(), LoginPage.class);
startActivity(i);
}
my LoginPage.java is previous activity.
If the connection is successfull it goes to the next activity ot doesnt give any error,
But if der is any prob with connection then i want progress bar should be stopped and go back to the LoginPage activity and also i want the error msg to be displayed.
From the above im getting some error.. Please help me out on this
Pass in and use the context from LoginPage. Also, use the 101010 button to format your code as code in your posts.
you can go up by using try catch mechanism where in your catch place your toast message and u can do it also by asynchronous task,
here simple code
private class Task_News_ArticleView extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
Bru_Sports_View.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
//here the condition to check login details
}
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
and u can also use try,catch in catch block you can place your toast message
with finsih() method