The application crashed suddenly. The logcat says that there is an error in doInBackground(). Please help.
Code
private class regjson extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "in prExecute", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
try{
Toast.makeText(getApplicationContext(), "in Background", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show() ;
}
return "All Done!";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "in Post Execute", Toast.LENGTH_SHORT).show();
}
}
and here is how i executed it
try{
new regjson().execute("hello");
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG);
}
You cant show a Toast in doInBackground().YOu cant update the UI from doInBackground(), instaed you have to do it in onPostExecute().
Read more about it in the docs
So, you have to remove
Toast.makeText(getApplicationContext(), "in Background", Toast.LENGTH_SHORT).show();
from your code.
If you are using this Toast for debugging purposes you can use Log.d() like,
Log.d("Key","in Background");
And you can see this Log message in your Logcat.
Related
I have to display different messages in progress dialog, when running in async task.
First I need to the display the message "Please wait", then "Downloading from server", then "Please wait for sometime".
I have tried with publishProgress but when I run the application, on my ProgressDialog, only the last message "Please wait for sometime" is displayed. How can I display the three messages?
private class Sample extends AsyncTask<String, String, String> {
ProgressDialog testdialog;
#Override
protected void onPreExecute() {
testdialog = new ProgressDialog(test.this);
testdialog.setTitle("Title");
testdialog.setMessage("Please wait ");
testdialog.setIndeterminate(false);
testdialog.setCancelable(false);
testdialog.setCanceledOnTouchOutside(false);
testdialog.show();
}
#Override
protected String doInBackground(String... urls) {
publishProgress("Downloading from server");
publishProgress("Please wait for sometime");
/* here I code the background downloading process*/
}
#Override
protected void onProgressUpdate(String... pro) {
testdialog.setMessage(pro[0]);
testdialog.setMessage(pro[1]);
}
#Override
protected void onPostExecute(String result) {
testdialog.dismiss();
}
}
try this code in doInBackground() it should display all messages with 2 seconds delay for each
except last one will remain on the dialog until dialog is dismissed or hidden
#Override
protected String doInBackground(String... urls) {
try {//this should let "Please wait " appears for 2 secs
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress("Downloading from server");
try {////this should let "Downloading from server" appears for 2 secs
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress("Please wait for sometime");
try {////this should let "Please wait for sometime" appears for 2 secs
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/* here i code the background downloading process*/
}
also for onProgressUpdate() the method is prepared to receive multi params, but you are sending only one, so no need to use pro[1], remove second setMessage() call
#Override
protected void onProgressUpdate(String... pro) {
testdialog.setMessage(pro[0]);
}
I am trying to send email using async method as shown below and everything is working fine..
Now I would like to display a dialog on successfull email.
This is my async code:
public void sending(View v) {
try {
LongOperation l=new LongOperation();
l.execute();
Toast.makeText(this, l.get(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
public class LongOperation extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try{GMailSender sender = new GMailSender("XXX#gmail.com","Pwd");
sender.sendMail("Sub",
"body",
"sender",
"recepient");
}
catch(Exception e){Log.e("error",e.getMessage(),e);return "Email Not Sent";}
return "Email Sent";
}
#Override
protected void onPostExecute(String result)
{
}
#Override
protected void onPreExecute()
{
}
#Override
protected void onProgressUpdate(Void... values)
{
}
In the above code if the mail is not sent I'm getting a toast as "Email Sent" and If not send the email I would get "Email Not Sent"
1)In the place of toasts I would like to display a dialog.
2)I have done it in onPostExecute and it worked fine.
But here comes the problem.Suppose if there is no internet connection and user clicks the button both the toast "Email Not sent" and the dialog is displaying after onPostExecute method.
I would only like to display the dialog.
So how do I modify the above code inorder to remove the toasts and only get the dialog for successfull and unsuccessfull email.
Here is my dialog code:
new AlertDialog.Builder(MainActivity.this)
.setTitle("Info")
.setMessage("Sample message.")
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Log.d("AlertDialog","Positive");
}}).show();
Still not completely sure I understand the problem but maybe this is what you want.
public void sending(View v) {
try {
LongOperation l=new LongOperation();
l.execute();
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
public class LongOperation extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try{GMailSender sender = new GMailSender("XXX#gmail.com","Pwd");
sender.sendMail("Sub",
"body",
"sender",
"recepient");
}
catch(Exception e){Log.e("error",e.getMessage(),e);return "Email Not Sent";}
return "Email Sent";
}
#Override
protected void onPostExecute(String result)
{
if ("Email Sent".equals(result))
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("Info")
.setMessage("Sample message.")
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Log.d("AlertDialog","Positive");
}}).show();
}
#Override
protected void onPreExecute()
{
}
#Override
protected void onProgressUpdate(Void... values)
{
}
I simply removed the Toast since you don't want that at all. Then I placed the Dialog code in onPostExecute() and checked the result passed to it from doInBackground(). I only showed it if the result is "Email Sent". You can change that to pass back a different result from doInBackground() if it isn't sent and show a different message in your Dialog.
Edit
I almost forgot to mention, you almost never want to use .get() on an AsyncTask. It is a blocking call which means everything will halt until your task is finished. You update the UI in any task method besides doInBackground() or you use an interface with a callback.
See this answer if you need an interface
i have created one simple login application which takes user name and password from sqlserver..it works fine...
i want during login process one progeress bar should be displayed using asyntask...
but i am unaware to use parameters in asyntask...if some one plzz tell me how to put my method in doInbackground of asyntask and what param should i use....
my code is;.....
public void save(){
initilize();
ResultSet rs = null;
String mylog=id.getText().toString();
String mypass=pass.getText().toString();
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
Toast.makeText(getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
} else
try {
if(rs.next()){
Intent i=new Intent(getApplicationContext(),Act2.class);
startActivity(i);
}
else if(rs.next()==false){
Toast.makeText(getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if it is possible that same method save() be kept inside doInbackground() of asyntask...
making a fast refactorization (note that this as it stand it's really bad practice and coding, you MUST refactor this code to be more maintanable and to avoid duplication):
public class MyAsyncTask extends AsyncTask<> {
private Activity activity;
boolean result;
private String myLog;
private String myPass;
private Connection connect;
public MyAsyncTask(Activity activity, Connection connect) {
this.activity = activity;
this.connect = connect;
}
#Override
protected void onPreExecute() {
//show your progress dialog
}
#Override
protected Object doInBackground(Object[] objects) {
ResultSet rs = null;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
initilize();
mylog=id.getText().toString();
mypass=pass.getText().toString();
}
});
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
}
});
} else
try {
if(rs.next()){
result = true;
}
else if(rs.next()==false){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
});
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
//hide your progress dialog
if(result == Boolean.TRUE){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i=new Intent(activity.getApplicationContext(),Act2.class);
activity.startActivity(i);
}
});
}
}
}
then in your Activity you do this:
MyAsyncTask a = new MyAsyncTask(this, connect); //im guessing "connect" is your Connection object
a.execute();
As i said i made this fast refactoring for the code to work but best practice and good implementation is not in consideration here.
Maybe, you could use a timer, to check if your
login is ready. As long as it is not, you Show your progress Bar. If its ready, you can close the Bar and start a new activity or anything. timers run can run on u UI thread.
regards :)
please see my code .. and if you can, tell me why my progressDialog stopped when the function is halfway done in the background, the screen hangs (nothing is displayed, the logcat shows all logs i put in the background function).
Then, right before the end, the progressDialog starts animating again and closes after a couple seconds (the function is finished and the result is displayed normally)
public class changeWall extends AsyncTask<Integer, Integer, Integer> {
protected Integer doInBackground(Integer... urls) {
int totalSize=0;
try {
if(s.loadBoolean() == false)
{
log("IF = false");
log("tempLogin = "+tempLogin);
log("tempPassword = "+tempPassword);
getNewResponse(tempLogin,tempPassword);
if(needSave)
{
s.saveBoolean(true);
}
}
else
{
if(s.loadLogin()==null)
{
getNewResponse(tempLogin,tempPassword);
}else
{
getNewResponse(s.loadLogin(),s.loadPassowrd());
}
}
parser.setLol(0);
parser.startParse(RESULT_STRING);
log("end parse");
} catch (ClientProtocolException e) {
log("internet connection lost");
} catch (IOException e) {
// TODO Auto-generated catch block
log(" connection lost");
}
log("count = "+parser.getFacebookId(1));
publishProgress();
totalSize=1;
log("end of start");
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
log("wall click ON PROGRESS UPDATE");
wall.setBackgroundResource(R.drawable.tabbuttonon);
messages.setBackgroundResource(0);
activity.setBackgroundResource(0);
profile.setBackgroundResource(0);
l1_1.setBackgroundResource(R.drawable.tabbuttononleft);
l1_2.setBackgroundResource(R.drawable.tabbuttononright);
l2_1.setBackgroundResource(0);
l2_2.setBackgroundResource(0);
l3_1.setBackgroundResource(0);
l3_2.setBackgroundResource(0);
l4_2.setBackgroundResource(0);
l4_2.setBackgroundResource(0);
wall.setTextColor(Color.BLACK);
messages.setTextColor(Color.WHITE);
profile.setTextColor(Color.WHITE);
activity.setTextColor(Color.WHITE);
try {
loadWall();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wallProgres.dismiss();
}
protected void onPostExecute(Long result) {
if(result==1)
{
log("end WallChange");
}
}
}
simple map as this showed :
----start progress(progress.show())
----start function
--- animation (progressDialog)
---animation(---)
---animation(---)
---FREEZ
---FREEZ(Function steel working normal, progressDialog in freeze mode)
---animation
---end function
---progress.dismis();//
similar problem i found here..(this problem = my problem but without download) Freezing UI Thread with AsyncTask
Regards,Peter.
It may not be correct but place
wallProgres.dismiss();
in onPostExecute rather than in onProgessUpdate method.
beacuse onProgressUpdate calls while running , but onPostExecute calls after execution.
Hope it helps..
place this line "wallProgres.dismiss()" in onPostExecute().
protected void onPostExecute(Long result) {
if(result==1)
{
log("end WallChange");
}
if(wallProgress.isShowing())
wallProgres.dismiss();
}
put this line
wallProgres.dismiss();
in onPostExecute() method
protected void onPostExecute(Long result) {
if(result==1)
{
log("end WallChange");
wallProgres.dismiss();
}
}
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