Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8550753
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T14:01:35+00:00 2026-06-11T14:01:35+00:00

I am creating a android application for sending sms using api. I am facing

  • 0

I am creating a android application for sending sms using api. I am facing force close problem when i am trying to cancel a async task and start another task. What i want to do is that if the message is not sent within 5 seconds the progress dialog should disappear and the async task should be cancelled and the new task should be started. I have written a code for that. Please help me resolve the error.

09-18 10:55:40.456: E/AndroidRuntime(3273): FATAL EXCEPTION: AsyncTask #1
09-18 10:55:40.456: E/AndroidRuntime(3273): java.lang.RuntimeException: An error   
occured while executing doInBackground()
09-18 10:55:40.456: E/AndroidRuntime(3273):     at   
android.os.AsyncTask$3.done(AsyncTask.java:200)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at 
java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at  
java.util.concurrent.FutureTask.setException(FutureTask.java:125)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at 
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at  
java.util.concurrent.FutureTask.run(FutureTask.java:138)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at 
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at 
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at java.lang.Thread.run(Thread.java:1019)
09-18 10:55:40.456: E/AndroidRuntime(3273): Caused by: java.lang.RuntimeException: Can't create 
handler inside thread that has not called Looper.prepare()
09-18 10:55:40.456: E/AndroidRuntime(3273):     at android.os.Handler.<init>(Handler.java:121)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at android.widget.Toast.<init>(Toast.java:68)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at android.widget.Toast.makeText(Toast.java:231)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at 
com.widgets.application.MainActivity$sendMessageAsync.doInBackground(MainActivity.java:260)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at 
com.widgets.application.MainActivity$sendMessageAsync.doInBackground(MainActivity.java:1)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at 
android.os.AsyncTask$2.call(AsyncTask.java:185)
09-18 10:55:40.456: E/AndroidRuntime(3273):     at 
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
09-18 10:55:40.456: E/AndroidRuntime(3273):     ... 4 more
09-18 10:55:43.432: E/WindowManager(3273): Activity com.widgets.application.MainActivity has leaked 
window com.android.internal.policy.impl.PhoneWindow$DecorView@40594188 that was originally added here
09-18 10:55:43.432: E/WindowManager(3273): android.view.WindowLeaked: Activity  
com.widgets.application.MainActivity has leaked window 
com.android.internal.policy.impl.PhoneWindow$DecorView@40594188 that was originally added here
09-18 10:55:43.432: E/WindowManager(3273):  at android.view.ViewRoot.<init>(ViewRoot.java:258)
09-18 10:55:43.432: E/WindowManager(3273):  at  
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
09-18 10:55:43.432: E/WindowManager(3273):  at 
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
09-18 10:55:43.432: E/WindowManager(3273):  at 
android.view.Window$LocalWindowManager.addView(Window.java:424)
09-18 10:55:43.432: E/WindowManager(3273):  at android.app.Dialog.show(Dialog.java:241)
09-18 10:55:43.432: E/WindowManager(3273):  at   
android.app.ProgressDialog.show(ProgressDialog.java:107)
09-18 10:55:43.432: E/WindowManager(3273):  at 
android.app.ProgressDialog.show(ProgressDialog.java:90)
09-18 10:55:43.432: E/WindowManager(3273):  at  
com.widgets.application.MainActivity.onClick(MainActivity.java:331)
09-18 10:55:43.432: E/WindowManager(3273):  at android.view.View.performClick(View.java:2485)
09-18 10:55:43.432: E/WindowManager(3273):  at android.view.View$PerformClick.run(View.java:9080)
09-18 10:55:43.432: E/WindowManager(3273):  at android.os.Handler.handleCallback(Handler.java:587)
09-18 10:55:43.432: E/WindowManager(3273):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-18 10:55:43.432: E/WindowManager(3273):  at android.os.Looper.loop(Looper.java:123)
09-18 10:55:43.432: E/WindowManager(3273):  at  
android.app.ActivityThread.main(ActivityThread.java:3683)
09-18 10:55:43.432: E/WindowManager(3273):  at java.lang.reflect.Method.invokeNative(Native Method)
09-18 10:55:43.432: E/WindowManager(3273):  at java.lang.reflect.Method.invoke(Method.java:507)
09-18 10:55:43.432: E/WindowManager(3273):  at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-18 10:55:43.432: E/WindowManager(3273):  at  
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-18 10:55:43.432: E/WindowManager(3273):  at dalvik.system.NativeStart.main(Native   Method)

Code

public class MainActivity extends Activity implements OnPanelListener, OnClickListener, OnItemClickListener {

final static int RQS_PICK_CONTACT = 1;
public static String sendSmsToNumber = "";

private EditText editText, editUserName, editPassword;
private ArrayList<Map<String, String>> mPeopleList;
private SimpleAdapter mAdapter;
private AutoCompleteTextView mTxtPhoneNo;
private Panel bottomPanel;
private Panel topPanel;
private Button btnsend;
private ProgressDialog pd;
//private String gateway_name;
private Spinner spinner1;
Context context;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editUserName = (EditText) findViewById(R.id.editTextUserName);
    editPassword = (EditText) findViewById(R.id.editTextPassword);
    mTxtPhoneNo = (AutoCompleteTextView) findViewById(R.id.mmWhoNo);
    mTxtPhoneNo.setTextColor(Color.BLACK);
    editText = (EditText) findViewById(R.id.editTextMessage);
    spinner1 = (Spinner) findViewById(R.id.spinnerGateway);
    btnsend = (Button) findViewById(R.id.btnSend);
    btnsend.setOnClickListener(this);
    mPeopleList = new ArrayList<Map<String, String>>();
    PopulatePeopleList();
    mAdapter = new SimpleAdapter(this, mPeopleList, R.layout.custcontview,
            new String[] { "Name", "Phone", "Type" }, new int[] {
                    R.id.ccontName, R.id.ccontNo, R.id.ccontType });
    mTxtPhoneNo.setAdapter(mAdapter);
    mTxtPhoneNo.setOnItemClickListener(this);
    Button buttonPickContact = (Button) findViewById(R.id.btnContact);
    buttonPickContact.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            startActivityForResult(intent, RQS_PICK_CONTACT);
        }
    });     
    init();
    Panel panel;
    topPanel = panel = (Panel) findViewById(R.id.mytopPanel);
    panel.setOnPanelListener(this);
    panel.setInterpolator(new BounceInterpolator(Type.OUT));

}

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data){
     super.onActivityResult(requestCode, resultCode, data);        
      if(requestCode == RQS_PICK_CONTACT){
          if(resultCode == RESULT_OK){
              Uri contactData = data.getData();
                Cursor cursor =  managedQuery(contactData, null, null, null, null);
                cursor.moveToFirst();
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                sendSmsToNumber = number;
                trimContactNumber();
                mTxtPhoneNo.setText(name + " <" + number + ">");
          }
      }
 }

public void trimContactNumber() {
    sendSmsToNumber = sendSmsToNumber.replace("-", "");
    sendSmsToNumber = sendSmsToNumber.replace("+91", "");
    if(sendSmsToNumber.length() > 10){
        sendSmsToNumber = sendSmsToNumber.substring(1, sendSmsToNumber.length());
    }
}

public void PopulatePeopleList() {
    mPeopleList.clear();
    Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    while (people.moveToNext()) {
        String contactName = people.getString(people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        String contactId = people.getString(people.getColumnIndex(ContactsContract.Contacts._ID));
        String hasPhone = people.getString(people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

        if ((Integer.parseInt(hasPhone) > 0)) {
            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
            while (phones.moveToNext()) {
                String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                String numberType = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                Map<String, String> NamePhoneType = new HashMap<String, String>();
                NamePhoneType.put("Name", contactName);
                NamePhoneType.put("Phone", phoneNumber);
                if (numberType.equals("0"))
                    NamePhoneType.put("Type", "Work");
                else if (numberType.equals("1"))
                    NamePhoneType.put("Type", "Home");
                else if (numberType.equals("2"))
                    NamePhoneType.put("Type", "Mobile");
                else
                    NamePhoneType.put("Type", "Other");
                mPeopleList.add(NamePhoneType);
            }
            phones.close();
        }
    }
    people.close();
    startManagingCursor(people);
}

public void onItemClick(AdapterView<?> av, View arg1, int index, long arg3) {
    @SuppressWarnings("unchecked")
    Map<String, String> map = (Map<String, String>) av.getItemAtPosition(index);
    String name = map.get("Name");
    String number = map.get("Phone");
    mTxtPhoneNo.setText(name + " <" + number + ">");
    sendSmsToNumber = number;
    trimContactNumber();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

private void init() {
    editUserName = (EditText) findViewById(R.id.editTextUserName);
    editPassword = (EditText) findViewById(R.id.editTextPassword);
    readPerson();
}

public void reset(View view) {
    PreferenceConnector.getEditor(this).remove(PreferenceConnector.NAME).commit();
    PreferenceConnector.getEditor(this).remove(PreferenceConnector.SURNAME).commit();
    PreferenceConnector.getEditor(this).remove(PreferenceConnector.AGE).commit();
    readPerson();
}

private void readPerson() {
    editUserName.setText(PreferenceConnector.readString(this,
            PreferenceConnector.NAME, null));
    editPassword.setText(PreferenceConnector.readString(this,
            PreferenceConnector.SURNAME, null));
}

public void save(View view) {
    String userNameTxt = editUserName.getText().toString();
    String PasswdTxt = editPassword.getText().toString();

    if (userNameTxt != null)
        PreferenceConnector.writeString(this, PreferenceConnector.NAME,userNameTxt);
    if (PasswdTxt != null)
        PreferenceConnector.writeString(this, PreferenceConnector.SURNAME,PasswdTxt);

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_T) {
        topPanel.setOpen(!topPanel.isOpen(), false);
        return false;
    }
    if (keyCode == KeyEvent.KEYCODE_B) {
        bottomPanel.setOpen(!bottomPanel.isOpen(), true);
        return false;
    }
    return super.onKeyDown(keyCode, event);
}

public void onPanelClosed(Panel panel) {
    String panelName = getResources().getResourceEntryName(panel.getId());
    Log.d("TestPanels", "Panel [" + panelName + "] closed");
}

public void onPanelOpened(Panel panel) {
    String panelName = getResources().getResourceEntryName(panel.getId());
    Log.d("TestPanels", "Panel [" + panelName + "] opened");
}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

public boolean isValid() {
    if (editUserName.getText().length() == 10 && editPassword.getText().length() != 0 && sendSmsToNumber.length() >= 10 && editText.getText().length() != 0) {
        return true;
    }
    return false;
}

private class sendMessageAsync extends AsyncTask<Void, Void, String>{
    String resultSet;

    @Override
    protected void onPreExecute(){
    }

    @Override
    protected String doInBackground(Void... arg0) {
        String usrname = editUserName.getText().toString();
        String usrPassword = editPassword.getText().toString();
        String number = sendSmsToNumber;
        String message = editText.getText().toString();
        String gateway_name = String.valueOf(spinner1.getSelectedItem());
        String gatewayToUse = gateway_name; 
        Log.i("Gateway", String.valueOf(spinner1.getSelectedItem()));
        String msgreciever = number;
        String testMessage = message;
        try{
            SmsSender.sendMessage(msgreciever, testMessage, usrname,usrPassword, gatewayToUse);
            resultSet = SmsSender.toastText;
            timerDelayRemoveDialog(5000, pd);               

        } catch(Exception ex){
            Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_SHORT).show();
        }
        return resultSet;
    }

    @Override
    protected void onPostExecute(String result){
        //super.onPostExecute(result);
        pd.dismiss();
        Toast.makeText(MainActivity.this,resultSet,Toast.LENGTH_SHORT).show();
    }

}

public void timerDelayRemoveDialog(long time, final Dialog d){
    new Handler().postDelayed(new Runnable() {
        public void run() {
            sendMessageAsync sma = new sendMessageAsync();
            sma.cancel(true);
            d.dismiss();
            Toast.makeText(MainActivity.this,"Sending Failed. Using Backup Server. Please Wait..",Toast.LENGTH_SHORT).show();
            sendBackupMessageAsync sbma = new sendBackupMessageAsync();
            sbma.execute();
        }
    }, time); 
}

private class sendBackupMessageAsync extends AsyncTask<Void, Void, String>{
    String resultSet;

    @Override
    protected void onPreExecute(){
    }

    @Override
    protected String doInBackground(Void... arg0) {         
        String usrname = editUserName.getText().toString();
        String usrPassword = editPassword.getText().toString();
        String number = sendSmsToNumber;
        String message = editText.getText().toString();
        String gateway_name = String.valueOf(spinner1.getSelectedItem());
        String gatewayToUse = gateway_name; 
        Log.i("Gateway", String.valueOf(spinner1.getSelectedItem()));
        String msgreciever = number;
        String testMessage = message;
        try{
            BackupSender.sendMessage(msgreciever, testMessage, usrname,usrPassword, gatewayToUse);
            resultSet = BackupSender.toastText;
        } catch(Exception ex){
            Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_SHORT).show();
        }
        return resultSet;
    }

    @Override
    protected void onPostExecute(String result){
        //super.onPostExecute(result);
        pd.dismiss();
        Toast.makeText(MainActivity.this,resultSet,Toast.LENGTH_SHORT).show();
    }

}

public void onClick(View v) {
    if (v == btnsend){
        if (!isOnline()){
            Toast.makeText(MainActivity.this,"No Internet Access..Cannot Send SMS",Toast.LENGTH_SHORT).show();
        } else if (!isValid()){
            Toast.makeText(MainActivity.this,"All fields are required. Try Again.",Toast.LENGTH_SHORT).show();
        } else {
            save(v);
            pd.setCancelable(true);
            pd = ProgressDialog.show(MainActivity.this, "Free Sms","Sending SMS. Please Wait", true); 
            sendMessageAsync sma = new sendMessageAsync();
            sma.execute();
        }
    }
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T14:01:36+00:00Added an answer on June 11, 2026 at 2:01 pm

    Caused by: java.lang.RuntimeException: Can’t create handler inside
    thread that has not called Looper.prepare() 09-18 10:55:40.456:
    E/AndroidRuntime(3273): at
    android.os.Handler.(Handler.java:121) 09-18 10:55:40.456:
    E/AndroidRuntime(3273): at
    android.widget.Toast.(Toast.java:68) 09-18 10:55:40.456:
    E/AndroidRuntime(3273): at
    android.widget.Toast.makeText(Toast.java:231) 09-18 10:55:40.456:
    E/AndroidRuntime(3273): at
    com.widgets.application.MainActivity$sendMessageAsync.doInBackground(MainActivity.java:260)

    You are calling Toast inside the doInBackground(). doInBackground() runs on a non-ui thread and you cannot do UI functions inside it.

    So, instead of Toasting anything inside doInBackGround(), set a flag there and when you come to onPostExecute(), check the value of that flag and make the Toast if necessary.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Actually, I am facing a problem in Android. I am creating an application that
I am creating an android application in flash builder 4 using 4.1 SDK on
I am creating an android application in which I am using table layout in
I'm creating an Android application (a game, to be more precise) and using AndEngine
I am creating an android application using Java. I have a boolean variable called
I'm trying to record sound by creating an android application. here is the code:
I am creating an Android application that connects to the Fogbugz XML API (sends
I am creating android/iphone application using Titanium Studio and right now stack with a
I was creating a opengl android application. I was trying to render a opengl
I'm creating a Android application which uses a Switch . I'm trying to listen

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.