AsyncTask in Android Studio - android

When i make my app run it doesn't go into onPostExecute() but when i debug it it works ,what can i do??I tried the thread.sleep() method but it doesn't help!!
Please what can i do in order for my AsyncTask to work while running
try {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
tempBook = backend.returnBook(book.getName(), book.getAuthor(), book.getEdition());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Void aVoid) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
book_provider.setId_Book(tempBook.getId_Book());
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
book_provider.setId_Provider(provider.getId_Provider());
book_provider.setPrice(Integer.parseInt(price.getText().toString()));
book_provider.setAmount_In_Stock(Integer.parseInt(quantity.getText().toString()));
try {
backend.addBook_Provider(book_provider);
} catch (Exception e) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(Add_Book.this);
builder1.setMessage(e.getMessage());
builder1.setIcon(R.drawable.ic_warning_black_24dp);
builder1.setTitle("WARNING!");
builder1.setCancelable(true);
builder1.setPositiveButton("Update this book",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent1 = new Intent(Add_Book.this, details_book_provider.class);
intent1.putExtra("book", book);
intent1.putExtra("provider", provider);
startActivity(intent1);
}
});
}

AsyncTask allows you to specify the return types of the objects which you want to use for the different methods. The declaration is AsyncTask
For this example I'm going to assume that tempBook is an instance of the class Book. You would need to do something like:
new AsyncTask<Void, Void, Book>() {
#Override
protected Book doInBackground(Void... params) {
try {
return backend.returnBook(
book.getName(),
book.getAuthor(),
book.getEdition()
);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Book result) {
book_provider.setId_Book(result.getId_Book());
}
}.execute();

First of all you should remove sleep in main thread as you've been told.
Also I'll recommend to move the code
book_provider.setId_Provider(provider.getId_Provider());
book_provider.setPrice(Integer.parseInt(price.getText().toString()));
book_provider.setAmount_In_Stock(Integer.parseInt(quantity.getText().toString()));
to the onPostExecute
You should understand that it's Async code and this code is executed before the command
book_provider.setId_Book(tempBook.getId_Book());

Related

Android AlertDialog freezes when saving data in database

In my App my I am using AlertDialog in Async. But it freezes at a point when data is saving in database. what can I do to keep it running? It runs perfectly for sometime but stops after certain time when database is accessed.
Here's my code:
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
return null;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
CheckInternetConnection internet = new CheckInternetConnection(
getApplicationContext());
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
return;
} else {
setUpdatedBarcodes();
}
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here after
data is saved in DB
}
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
DB operations should be done in the background thread. Put it in doInBackground() method too.
I modify your code. may it helps..
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
} else {
setUpdatedBarcodes();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
when saving data in database don't do it on main thread do it on background thread. try code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do your work
}
},0);
or
new Thread(new Runnable() {
public void run() {
// do your work here
}
}).start();

My activity keep show the dialog, It seem don't do the doInBackground

My activity keep show the dialog, It seem don't do the doInBackground. It keep should the "Loading" screen .
Here is my code :
private class MapTask extends AsyncTask<Void, Void, Void> {
protected ProgressDialog dialog;
protected Context context;
public MapTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.dialog = new ProgressDialog(context, 1);
this.dialog.setMessage("Loading");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
try {
String countryName=country.getTitle();
List<Address> address = new Geocoder(context).getFromLocationName(countryName, 1);
if (address == null) {
Log.e(null, "Not found");
} else {
Address loc = address.get(0);
Log.e(null, loc.getLatitude() + " " + loc.getLongitude());
LatLng pos = new LatLng(loc.getLatitude(), loc.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 6));
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (Exception e) {
Log.v("ASYNC", "ERROR : " + e);
e.printStackTrace();
}
return null;
}
}
Could somebody help me?
You are not calling dialog.dismiss() anywhere. You should do it in the onPostExecute of your AsyncTask:
#Override
protected void onPostExecute(Void... aVoid) {
dialog.dismiss();
}
In fact it is doing the doInBackground stuff, the problem is that you aren't dismissing the dialog in onPostExecute() method
Just add dialog.dismiss() in onPostExecute method.

progress dialog displays after task is finished in asynctask

Hi i want to display progressdialog until a command is executed through telnet.
so i use asynctask for that purpose.
private class AsyncAction extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pd.dismiss();
}
// pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
And i call asynctask in oncreate() like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
The problem is that i could not see progressdialog until command executes.
please help me solve the issue.
Thanks in advance.
EDIT
The code to send and read command
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length()-1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar)
{
if (sb.toString().endsWith(pattern))
{
if (sb.toString().contains("cdkk"))
{
disconnect();
break;
}
else
{
return sb.toString();
}
}
else
{
disconnect();
break;
}
}
else if(sb.toString().contains("Failed"))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String error="Invalid username or password!";
alertbox.setMessage(error);
alertbox.setTitle("Error");
alertbox.show();
System.out.println("bad user name");
disconnect();
break;
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently you are trying to do Network operations from onPostExecute because this method called from UI Thread . change your code as to get work in proper way
private class AsyncAction extends AsyncTask<String, Void, String>
{
public static boolean status=false;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
// make status true or false if command successfully executed
status=true;
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
// check status if true then show AlertDialog
if(status==true){
AlertDialog.Builder alertbox =
new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
else{
// your code here
}
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
You need to show the progress bar in onPreExecute() do the work in doInBackground() and then hide the progress bar in onPostExecute(). onPreExecute() and onPostExecute() are both executed on the main thread, where as doInBackground is executed in the background.
You are doing your work on onPostExecute() method which should be inside doInBackground()
show your progress dialog inside onPreExecute() and dismiss inside onPostExecute().

progress dialog circle only showing after task

i've an progress circle that is set inside an AsyncTask. It shows for about a second as the asynctask is executing, then disappears. once the task is completed if i press the back button the circle shows for a long time. why is this?
private class AsyncGetRota extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(NfcscannerActivity.this,
"Connecting to Server"," retrieving rota...", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(String... params) {
try {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
[update]
getRota.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "onclicked getRota");
String[] params = new String[]{"36", "18-09-2012"};
AsyncGetRota agr = new AsyncGetRota();
agr.execute(params);
for(int i = 0; i < 60; i++){
if(agr.isCancelled() == true){
Log.e(TAG, "asyncTask is finished");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end of for loop
Intent intent = new Intent(NfcscannerActivity.this,
GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", rotaArray);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}// end of onclick
});
...
new MyAsyncTask().execute(string);
...
}
class MyAsyncTask extends AsyncTask<String, Void, Whatever > {
...
#Override
protected Whatever doInBackground(String... params) {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
return rotaArray;
}
#Override
protected void onPostExecute(Whatever result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
Intent intent = new Intent(NfcscannerActivity.this, GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", result);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}
}
You should let the execution continue after you start the AsyncTask, and not block it using some loop or something..
try to implement it like this:
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Processing...");
dialog.show();
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
};
that's always works for me
Couple of problems here, you do not initialize ProgressDialog, initialize a constructor that initializes you ProgressDialog like this...
public AsyncGetRota(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
Then in onPostExecute check if your ProgressDialog is null, like this
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
}

To use ProgressDialog till GridView gets loaded from webservice

I am fetching Image and Text for GridView from a webservice, so its takes some time to display the GridView. I want to show a ProgressDialog till Grid gets fully loaded. What I have done till now is as below:
public class PCGridMain extends Activity
{
WebService web = new WebService();
private GridView gridView;
ProgressDialog dialog;
Bitmap icon;
int i, total;
URL url= null;
List<GridItem> list;
#Override
public void onCreate(Bundle grid)
{
super.onCreate(grid);
dialog = ProgressDialog.show(PCGridMain.this, "Loading...", "Loading App, Please wait.", true);
DialogWork dWork = new DialogWork();
dWork.execute();
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridView1);
web.WebService1();
total = web.totalService;
list = new ArrayList<GridItem>();
for(i=0; i<total; i++)
{
Log.v("Try Block", "See what we get:-");
try
{
Log.v("GridMain", "try url" + Integer.toString(i));
url = new URL(web.arr[i][2]);
}
catch (MalformedURLException e)
{
Log.v("GridMain", "catch MalformedURLException" + Integer.toString(i));
e.printStackTrace();
}
try
{
Log.v("GridMain", "try BitmapFactory" + Integer.toString(i));
icon = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
Log.v("GridMain", "catch IOException" + Integer.toString(i));
e.printStackTrace();
}
list.add(new GridItem(icon, web.arr[i][1])); // Adding Icon & LAbel
}
gridView.setAdapter(new GridAdapter(this, list));
gridView.setOnItemClickListener(Itemlistener);
}
private OnItemClickListener Itemlistener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
ViewHolder holder = (ViewHolder)view.getTag();
if(holder == null)
{
return;
}
Toast.makeText(PCGridMain.this, holder.label.getText(), Toast.LENGTH_SHORT).show();
Log.v("GridMain", "Intent Creation");
Intent intent = new Intent(view.getContext(), ShowService.class); Log.v("GridMain", "Intent Created");
intent.putExtra("ServiceId", web.arr[position][0]); Log.v("GridMain", "ValueAdded Sid");
intent.putExtra("SName", holder.label.getText()); Log.v("GridMain", "ValueAdded SName");
startActivity(intent);
}
};
class DialogWork extends AsyncTask<URL, Integer, Long>
{
protected Long doInBackground(URL... params)
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Long result)
{
try
{
//setContentView(R.layout.main);
//gridView.setAdapter(new GridAdapter(PCGridMain.this, list));
dialog.dismiss();
}
catch (Exception e)
{
e.printStackTrace();
dialog.dismiss();
}
}
}
Please tell me that what code has to be placed at what exact location, whenever I do some changes, it either shows no effect or App closes due to some issue.
Thanks,
Haps.
Try to put all rendering part from server in doInBackground() and set the adapter in onPostExecute() . And even start the progressdialog in onPreExecute() in and dismiss it on onPostExecute() but not in onCreate(). I think it will solve ur problem....
This should be your inner AsyncTask class, change parameters as you need.
private class yourTask extends AsyncTask<Void, Void, ArrayList> {
String message;
ProgressDialog dialog;
public refreshTask(String message) {
this.message = message;
this.dialog = new ProgressDialog(PCGridMain.this);
}
#Override
protected void onPreExecute() {
dialog.setMessage(message);
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList doInBackground(String... params) {
// Some work
}
#Override
protected void onPostExecute(ArrayList result) {
if(dialog.isShowing())
dialog.dismiss();
}
}
So you may call this class like:
new yourTask('Dialog message').execute();
I hope it solves your issue.
Here I am giving the complete answer to my question, So that it may help others to make it done easily...
public class PCGridMain extends Activity
{
WebService web = new WebService();
private GridView gridView;
ProgressDialog dialog;
Bitmap icon;
int i, total;
URL url= null;
List<GridItem> list;
#Override
public void onCreate(Bundle grid)
{
super.onCreate(grid);
Log.v("GridMain", "setContent");
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridView1);
DialogWork dWork = new DialogWork();
dWork.execute();
}
private void ForLoop()
{
for(i=0; i<total; i++)
{
Log.v("Try Block", "See what we get:-");
try
{
Log.v("GridMain", "try url" + Integer.toString(i));
url = new URL(web.arr[i][2]);
}
catch (MalformedURLException e)
{
Log.v("GridMain", "catch MalformedURLException" + Integer.toString(i));
e.printStackTrace();
}
try
{
Log.v("GridMain", "try BitmapFactory" + Integer.toString(i));
icon = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
Log.v("GridMain", "catch IOException" + Integer.toString(i));
e.printStackTrace();
}
list.add(new GridItem(icon, web.arr[i][1])); // Adding Icon & LAbel
}
}
private OnItemClickListener Itemlistener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
ViewHolder holder = (ViewHolder)view.getTag();
if(holder == null)
{
return;
}
Toast.makeText(PCGridMain.this, holder.label.getText(), Toast.LENGTH_SHORT).show();
Log.v("GridMain", "Intent Creation");
Intent intent = new Intent(view.getContext(), ShowService.class); Log.v("GridMain", "Intent Created");
intent.putExtra("ServiceId", web.arr[position][0]); Log.v("GridMain", "ValueAdded Sid");
intent.putExtra("SName", holder.label.getText()); Log.v("GridMain", "ValueAdded SName");
startActivity(intent);
}
};
class DialogWork extends AsyncTask<URL, Integer, String>
{
protected void onPreExecute()
{
Log.v("GridMain", "PreExecute()");
dialog = ProgressDialog.show(PCGridMain.this, "Loading...", "Loading App, Please wait.", false, true);
}
protected Long doInBackground(URL... params)
{
String response = "";
try
{
Log.v("GridMain", "doInBackground");
response = web.WebService1();
total = web.totalService;
}
catch (InterruptedException e)
{
Log.v("GridMain", "InterruptedException");
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String result)
{
try
{
// Response is in RESULT_VAR
Log.v("GridMain", "onPostExecute");
list = new ArrayList<GridItem>();
ForLoop();
gridView.setAdapter(new GridAdapter(PCGridMain.this, list));
gridView.setOnItemClickListener(Itemlistener);
dialog.dismiss();
}
catch (Exception e)
{
Log.v("GridMain", "Exception e");
e.printStackTrace();
dialog.dismiss();
}
}
}
}
I have used it as according to my needs, its just for the help, the complete code might give problem to you. So just take it as a reference.
Thanks & Regards,
Haps.
try dialog with this code else code seems working
dialog= new ProgressDialog(this);
dialog.setMessage("Loading");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.show();

Categories

Resources