error while creating a alertbox during thread execution - android

i am trying to create alertbox in a thread but getting error here is my code to thread and alertbox ,this alertbox successfully working out of thread.posting code and error logs ,help me.
Thread paypalThread = new Thread() {
#Override
public void run() {
try {
PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo(
"com.mothistorycheck", 0);
String appFile = appInfo.sourceDir;
long installed = new File(appFile).lastModified();
Date date = new Date(installed * 1000L);
Date currentDate = Calendar.getInstance().getTime();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, 1);
Date installedPlusYear = cal.getTime();
System.out.println(installedPlusYear);
if (currentDate.compareTo(date)==-1) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
.setNegativeButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
}).create();
// Setting Dialog Title
alertDialog.setTitle("Alert");
// Setting Dialog Message
alertDialog
.setMessage("Either MOT test number or Document Reference Number should be entered!");
alertDialog.setCancelable(true);
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Showing Alert Message
alertDialog.show();
return;
}else
System.out.println("000000");
// int comparison2 = oneYearFromNow.compareTo(date);
// sleep(31536000);
}
catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// finish();
Intent i = new Intent(getApplicationContext(),
SplashActivity.class);
//startActivity(i);
}
}
};
paypalThread.start();
Here log details
10-24 12:32:23.462: E/AndroidRuntime(20705): FATAL EXCEPTION: Thread-5842
10-24 12:32:23.462: E/AndroidRuntime(20705): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
10-24 12:32:23.462: E/AndroidRuntime(20705): at android.os.Handler.<init>(Handler.java:121)
10-24 12:32:23.462: E/AndroidRuntime(20705): at android.app.Dialog.<init>(Dialog.java:107)
10-24 12:32:23.462: E/AndroidRuntime(20705): at android.app.AlertDialog.<init>(AlertDialog.java:114)
10-24 12:32:23.462: E/AndroidRuntime(20705): at android.app.AlertDialog$Builder.create(AlertDialog.java:913)
10-24 12:32:23.462: E/AndroidRuntime(20705): at com.mothistorycheck.MainActivity$1.run(MainActivity.java:132)

This occur because you can manipulate view inside a thread that is not UI main thread, you can use Handler to perform your dialog appear, also see Handler Example and Handling View inside Handler

You must need to create AlertDialog inside UI thread else it will never work. If you are in different thread use MessageHandler or can use runOnUiThread(using runnable) to create your dialog inside.
Create a handler inside onCreate(), or onResume()
..onCreate(){
...mHandler=new Handler();
}
Then inside your Thread() just use :
mHandler.post(new Runnable{
public void run(){
//Be sure to pass your Activity class, not the Thread
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
//... setup dialog and show
}
});

As already mentioned, you can't make any changes to UI outside of the UI thread. I suggest you use an AsyncTask & create your dialog in onPostExecute callback. this is how you can use it:
public void verifyPaypal() {
PayPalVerifyTask task = new PayPalVerifyTask();
task.execute((Void) null);
}
public class PayPalVerifyTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo(
"com.mothistorycheck", 0);
String appFile = appInfo.sourceDir;
long installed = new File(appFile).lastModified();
Date date = new Date(installed * 1000L);
Date currentDate = Calendar.getInstance().getTime();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, 1);
Date installedPlusYear = cal.getTime();
System.out.println(installedPlusYear);
if (currentDate.compareTo(date)==-1) {
return true; // this will be passed to onPostExecute
}else
System.out.println("000000");
// int comparison2 = oneYearFromNow.compareTo(date);
// sleep(31536000);
return false;
}
catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// finish();
Intent i = new Intent(getApplicationContext(),
SplashActivity.class);
//startActivity(i);
}
}
#Override
protected void onPostExecute(final Boolean show_alert) {
if (show_alert) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
.setNegativeButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
}).create();
// Setting Dialog Title
alertDialog.setTitle("Alert");
// Setting Dialog Message
alertDialog
.setMessage("Either MOT test number or Document Reference Number should be entered!");
alertDialog.setCancelable(true);
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Showing Alert Message
alertDialog.show();
}
}
}
run verifyPaypal() to start the task.

Related

Android runOnUiThread to show progress dialog and to populate views

I usually work on .Net but I need to develop an Android app. So I am new on Android, sorry for mistakes in advance! :)
Here is my story,
I am populating a customer list(creating ui elements in code behind) with views in a button click. I am doing that pulling datas from database. So it takes some time to pull the data and creating views. What I wanna do is showing a progress dialog while customer list is being populated. Currently I am able to make it run. But the problem is it doesn't show the progress dialog immediately, then customerlist and progress dialog are displayed at the same time.
Here is my button click;
public void ShowCustomers(View view){
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.setTitle("Title");
dialog.setMessage("Loading...");
if(!dialog.isShowing()){
dialog.show();
}
}
});
new Thread() {
public void run() {
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
PopulateRecentGuests(); //Creates customer list dynamically
dialog.dismiss();
}
});
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}.start();
}
And populating the customers;
public void PopulateRecentGuests(){
LinearLayout customers = (LinearLayout)findViewById(R.id.customers);
String query = "SELECT * from Table";
ModelCustomer customerModel = new ModelCustomer();
ArrayList<HashMap<String, String>> recentGuests = customerModel.RetrievingQuery(query);
customersCount = recentGuests.size();
Context context = getApplicationContext();
if(customersCount < 1)
Toast.makeText(context, "There is no available customer in database!", Toast.LENGTH_LONG);
else if(!recentGuests.get(0).containsKey("err")) {
for(int i = 0; i < recentGuests.size(); i++){
HashMap<String, String> guest = recentGuests.get(i);
Button button = new Button(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(0,5,0,5);
button.setLayoutParams(params);
button.setWidth(800);
button.setHeight(93);
button.setTag(guest.get("id"));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("New button clicked! ID: " + v.getTag());
Intent intent = new Intent(getApplicationContext(), ProductPageActivity.class);
intent.putExtra("CustomerID", v.getTag().toString());
startActivity(intent);
}
});
button.setBackgroundColor(Color.parseColor("#EFEFEF"));
button.setText(guest.get("FirstName") + " " + guest.get("LastName") + " " + guest.get("GuideName"));
button.setTextColor(Color.BLACK);
button.setTextSize(20);
button.setEnabled(false);
customers.addView(button); // customers is a linear layout and button is being added to customers
Button guest_list_btn = (Button)findViewById(R.id.guest_list_btn);
guest_list_btn.setEnabled(true);
}
}
else{
CharSequence text = recentGuests.get(0).get("err");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Button guest_list_btn = (Button)findViewById(R.id.guest_list_btn);
Button guest_list_close_btn = (Button)findViewById(R.id.guest_list_close_btn);
customers.setVisibility(View.VISIBLE);
AnimationSet aset = new AnimationSet(true);
aset.setFillEnabled(true);
aset.setInterpolator(new LinearInterpolator());
AlphaAnimation alpha = new AlphaAnimation(0.0F, 1.0F);
alpha.setDuration(400);
aset.addAnimation(alpha);
TranslateAnimation trans = new TranslateAnimation(200, 0, 0, 0);
trans.setDuration(400);
aset.addAnimation(trans);
customers.startAnimation(aset);
guest_list_btn.setEnabled(false);
guest_list_close_btn.setEnabled(true);
for(int i = 0; i < customers.getChildCount(); i++){
View child = customers.getChildAt(i);
child.setEnabled(true);
}
}
After my research, I understand that runonuithread is called after looper. My question is How can I display the progress dialog immediately and then I can populate the customer list (creating ui elements). By the way, I tried to do that with asynctask first but I wasn't able to.
Thans in advance!
But the problem is it doesn't show the progress dialog immediately,
then customerlist and progress dialog are displayed at the same time.
That's because you do the long operation(and closing the dialog sequentially) on the main UI thread. Instead you should separate things between retrieving the data(which takes time) and building the views(along with closing the dialog).
//...
new Thread() {
public void run() {
// do the long operation on this thread
final ArrayList<HashMap<String, String>> recentGuests = customerModel.RetrievingQuery(query);
// after retrieving the data then use it to build the views and close the dialog on the main UI thread
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
// remove the retrieving of data from this method and let it just build the views
PopulateRecentGuests(recentGuests);
dialog.dismiss();
}
});
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}.start();

Kill a thread in previous activity in android

I have a thread in Activity A which starts Activity B after 30 seconds.But user can also go to activity B before that time on a button click.I want kill thread in Activity A if the user clicks that button so that Activity B wont get started again. I tried to kill thread if button is clicked, but it is of no use and finish() is also not killing that thread after navigating to B.
Thread t=new Thread()
{
public void run()
{
try {
sleep(5000);
currentClass = Class.forName("com.crazydna.memorizethepic.Level"+levelNumber);
Intent ourIntent = new Intent(PictureDisplay.this, currentClass);
startActivity(ourIntent);
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
Log.e("TAG","Error: " +e.getStackTrace());
//e.printStackTrace();
AlertDialog.Builder alertDialog=new AlertDialog.Builder(PictureDisplay.this);
alertDialog.setTitle("Alert!!!");
alertDialog.setMessage(" "+e.toString());
alertDialog.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alertDialog.show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
AlertDialog.Builder alertDialog=new AlertDialog.Builder(PictureDisplay.this);
alertDialog.setTitle("Alert!!!");
alertDialog.setMessage(" "+e.toString());
alertDialog.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
};
t.start();
just put a boolean variable isStarted as instance variable, Check this within thread
try {
sleep(5000);
if(!isStarted)
{
currentClass =
Class.forName("com.crazydna.memorizethepic.Level"+levelNumber);
Intent ourIntent = new Intent(PictureDisplay.this, currentClass);
startActivity(ourIntent);
}
}
On button click set isStarted to true
You have to options.
The first option is to shorten the time for your sleep() function and enclose it in a while() block where you monitor a cancellation variable, this variable would be in your class definition.
Boolean run_my_timer = true;
while (run_my_timer)
{
sleep(1000); // sleep 1 second only
currentClass = Class.forName("com.crazydna.memorizethepic.Level"+levelNumber);
Intent ourIntent = new Intent(PictureDisplay.this, currentClass);
startActivity(ourIntent);
}
And add a line that set's this variable to false if the user clicks the button
run_my_timer = false;
This would make the thread exit.
The second option, which would be more elegant is create a Timer, instead of a thread, if the user presses the button to open ActivityB you cancel the timer, with the Timer's cancel() method.

Android Handler - not working properly

I want to create a dialogBuilder with a text field and a button on it. The idea is to make the program wait for any further actions until the text in the field is entered and the OK button is clicked. Below is the code:
private static final Object wait = new int[0];
private static String result = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler h = new Handler();
final Context context = MainActivity.this;
h.post(new Runnable() {
public void run() {
final Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(R.string.app_name);
final LinearLayout panel = new LinearLayout(context);
panel.setOrientation(LinearLayout.VERTICAL);
final TextView label = new TextView(context);
label.setId(1);
label.setText(R.string.app_name);
panel.addView(label);
final EditText input = new EditText(context);
input.setId(2);
input.setSingleLine();
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_URI
| InputType.TYPE_TEXT_VARIATION_PHONETIC);
final ScrollView view = new ScrollView(context);
panel.addView(input);
view.addView(panel);
dialogBuilder
.setCancelable(true)
.setPositiveButton(R.string.app_name,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
result = input.getText().toString();
synchronized (wait) {
wait.notifyAll();
}
dialog.dismiss();
}
}).setView(view);
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
result = null;
synchronized (wait) {
wait.notifyAll();
}
}
});
dialogBuilder.create().show();
}
});
String localResult = null;
try {
synchronized (wait) {
Log.d("Waiting", "Waiting " + localResult);
wait.wait();
}
localResult = result;
result = null;
if (localResult == null) {
// user is requesting cancel
throw new RuntimeException("Cancelled by user");
}
Log.d("RESULT ", "RESULT " + localResult);
} catch (InterruptedException e) {
localResult = result;
result = null;
if (localResult == null) {
// user is requesting cancel
Log.d("CANCELED ", "CANCELED " + localResult);
throw new RuntimeException("Cancelled by user");
}
}
Log.d("RESULT AFTER THE DIALOG", "RESULT AFTER THE DIALOG " + result);
}
The program is going to Log.d("Waiting", "Waiting " + localResult); and after that just waiting. NO DIALOG BUILDER IS SHOWN on the activity window. I used the debug mode and saw that the program flow is not entering the run() method, but the value of the Handler.post() is true. And for this reason the dialog is not shown, and the program is waiting.
I have tried to remove the moment with waiting (remove the Handler.post()), just to see if the dialog will show, and it showed and all moved well, but the result was not I am needing - I want the program to wait the input from the dialog ... I am really out of ideas.
Would you please give me some suggestions as I am really out of ideas.
Thanks a lot!
Handlers don't run in a separate thread. So when you call wait() :
synchronized (wait) {
Log.d("Waiting", "Waiting " + localResult);
wait.wait();
}
It waits indefinitely since the handler runs on the same thread as the current thread. Your Runnable can only be executed after the onCreate() method finishes but this will never happen because you just called wait().
You should reconsider your idea and find a workaround (for example, show the dialog the usual way and disable the "OK" button as long as the user does not enter a valid text). But calling wait() on the UI thread cannot go well.
You should be running the display of the Dialog in the UI Thread, not a seperate thread.
An example would be something like this:
In the onCreate()
runOnUiThread(new Runnable() {
#Override
public void run() {
// Display progress dialog when loading contacts
dialog = new ProgressDialog(this);
// continue with config of Dialog
}
});
// Execute the Asynchronus Task
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// code to execute in background
return null;
}
#Override
protected void onPostExecute(Void result) {
// Dismiss the dialog after inBackground is done
if (dialog != null)
dialog.dismiss();
super.onPostExecute(result);
}
}.execute((Void[]) null);
Specifically what is happening here is the Dialog is being displayed on the UI thread and then the AsyncTask is executing in the background while the Dialog is running. Then at the end of the execution we dismiss the dialog.

showing progress bar in alert dialog

I have an alert dialog box in my application for login authentication. While sending the request i want to show a progress bar and want to dismiss if the response is success.please help me if anyone knows.Iam using the below code:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout login = new LinearLayout(this);
TextView tvUserName = new TextView(this);
TextView tvPassword = new TextView(this);
TextView tvURL = new TextView(this);
final EditText etUserName = new EditText(this);
final EditText etPassword = new EditText(this);
final EditText etURL = new EditText(this);
login.setOrientation(1); // 1 is for vertical orientation
tvUserName.setText(getResources().getString(R.string.username));
tvPassword.setText(getResources().getString(R.string.password));
tvURL.setText("SiteURL");
login.addView(tvURL);
login.addView(etURL);
login.addView(tvUserName);
login.addView(etUserName);
login.addView(tvPassword);
etPassword.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
login.addView(etPassword);
alert.setView(login);
alert.setTitle(getResources().getString(R.string.login));
alert.setCancelable(true);
alert.setPositiveButton(getResources().getString(R.string.login),
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
int whichButton) {
strhwdXml = etURL.getText().toString();
strUserName = etUserName.getText().toString();
XmlUtil.username = strUserName;
strPassword = etPassword.getText().toString();
if ((strUserName.length() == 0)
&& (strPassword.length() == 0)
&& (strhwdXml.length() == 0)) {
Toast.makeText(
getBaseContext(),
getResources().getString(
R.string.userPassword),
Toast.LENGTH_SHORT).show();
onStart();
} else {
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor prefsEditor = prefs
.edit();
try {
StringBuffer inStreamBuf = new StringBuffer();
inStreamBuf = XmlUtil
.getLoginAuthResponse(strUserName,
strPassword, strhwdXml);
strXmlResponse = inStreamBuf.toString();
Log.e("Response:", strXmlResponse);
String parsedXML = ParseResponse(strXmlResponse);
if (parsedXML
.equalsIgnoreCase(getResources()
.getString(R.string.success))) {
}
It might be easier to use this
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
You can read more about progress dialogs here
To cancel would be
dialog.dismiss();
This class was deprecated in API level 26. ProgressDialog is a modal
dialog, which prevents the user from interacting with the app. Instead
of using this class, you should use a progress indicator like
ProgressBar, which can be embedded in your app's UI. Alternatively,
you can use a notification to inform the user of the task's progress.For more details Click Here
Since the ProgressDialog class is deprecated, here is a simple way to display ProgressBar in AlertDialog:
Add fields in your Activity:
AlertDialog.Builder builder;
AlertDialog progressDialog;
Add getDialogProgressBar() method in your Activity:
public AlertDialog.Builder getDialogProgressBar() {
if (builder == null) {
builder = new AlertDialog.Builder(this);
builder.setTitle("Loading...");
final ProgressBar progressBar = new ProgressBar(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
progressBar.setLayoutParams(lp);
builder.setView(progressBar);
}
return builder;
}
Initialize progressDialog:
progressDialog = getDialogProgressBar().create();
Show/Hide AlertDialog whenever u want using utility methods:
progressDialog.show() and progressDialog.dismiss()
If you want the progress bar to show, try the following steps and also you can copy and paste the entire code the relevant portion of your code and it should work.
//the first thing you need to to is to initialize the progressDialog Class like this
final ProgressDialog progressBarDialog= new ProgressDialog(this);
//set the icon, title and progress style..
progressBarDialog.setIcon(R.drawable.ic_launcher);
progressBarDialog.setTitle("Showing progress...");
progressBarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//setting the OK Button
progressBarDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,
int whichButton){
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT).show();
}
});
//set the Cancel button
progressBarDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton){
Toast.makeText(getApplicationContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
}
});
//initialize the dialog..
progressBarDialog.setProgress(0);
//setup a thread for long running processes
new Thread(new Runnable(){
public void run(){
for (int i=0; i<=15; i++){
try{
Thread.sleep(1000);
progressBarDialog.incrementProgressBy((int)(5));
}
catch(InterruptedException e){
e.printStackTrace();
}
}
//dismiss the dialog
progressBarDialog.dismiss();
}
});
//show the dialog
progressBarDialog.show();
The cancel button should dismiss the dialog.
Try below code
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
// write your request code here
**StringBuffer inStreamBuf = new StringBuffer();
inStreamBuf = XmlUtil
.getLoginAuthResponse(strUserName,
strPassword, strhwdXml);
strXmlResponse = inStreamBuf.toString();
Log.e("Response:", strXmlResponse);
String parsedXML = ParseResponse(strXmlResponse);
if (parsedXML
.equalsIgnoreCase(getResources()
.getString(R.string.success))) {**
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(ShowDescription.this,
"File successfully downloaded", Toast.LENGTH_LONG)
.show();
imgDownload.setVisibility(8);
} else {
Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
.show();
}
}
}
and call this in onclick event
new DownloadingProgressTask().execute();

thread not running in background

i am calling this function from the menu and calls the upload(item) function to pass the index of the selected priority.
public void showPriorityDialog()
{
final CharSequence[] priority = {"1 Hour", "12 Hours", "24 Hours", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Priority");
builder.setItems(priority, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(item != 3)
upload(item);
}
});
AlertDialog alert = builder.create();
alert.show();
}
however, whenever i call the upload function, the thread doesn't run in background, and the OS thinks that the app is not responding due to executing timeout.
public void upload(int priority)
{
final int _priority = priority;
uploadThread = new Thread()
{
#Override
public void run()
{
try
{
super.run();
mHandler.post(new Runnable() {
#Override
public void run() {
try
{
//ftp commands...
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString() , Toast.LENGTH_SHORT).show();
}
}
});
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString() , Toast.LENGTH_SHORT).show();
}
}
};
uploadThread.start();
}
am i doing something wrong? TIA
When you do mHandler.post(), your entire Runnable executes on UI thread and your background thread just exits. To fix, do FTP before posting to handler. Then do mHandler.post() to have Toast appear. Note that you catch also need to display Toast via post.

Categories

Resources