I need to make an app that sends an SMS message after showing a progress bar in increments of 10. I have the action bar set up and I think I should use AsyncTask? The user is inputing number and message into the main activity, and that's where I have the SendSMS method set up, not sure how to make this work so that it forwards to AsyncTask and calls on that method there.
public class MainActivity extends AppCompatActivity {
private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;
private static final String SMS_SENT = "SMS_SENT";
private static final String SMS_DELIVERED= "SMS_DELIVERED";
private EditText etPoruka;
private EditText etBroj;
private ProgressDialog progressDialog;
private Context context = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
}
private void initWidgets() {
etPoruka = findViewById(R.id.etPoruka);
etBroj = findViewById(R.id.etBroj);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
MyAsyncTask<Void, Void, Void> updateTask = new MyAsyncTask<Void, Void, Void>(context);
updateTask.execute();
break;
case R.id.action_sent:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
// BROADCAST RECEIVER ??
break;
case R.id.action_received:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
//BROADCAST RECEIVER ??
//BOUND SERVICE
break;
case R.id.action_exit:
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Close app");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return true;
}
public void sendSMS() {
try{
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(etBroj.getText().toString(),null,etPoruka.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "SMS sent successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
ASYNCTASK
public class MyAsyncTask extends
AsyncTask {
private final String DIALOG_MESSAGE = "Sending message";
private ProgressDialog mDialog = null;
private void setDialog(Context context) {
this.mDialog = new ProgressDialog(context);
this.mDialog.setMessage(DIALOG_MESSAGE);
this.mDialog.setCancelable(false);
}
public MyAsyncTask(Context context) {
this.setDialog(context);
}
#Override
protected void onPreExecute() {
this.mDialog.show();
}
#Override
protected Result doInBackground(Params... arg0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Result result) {
if (this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} }
You can create an Interface and implement in your MainActivity.
For More Details Please check these answers:
how do i send data back from onPostExecute in an AsyncTask?
How to pass data from an asynchronous task to an activity that called it?
Related
I am working on an Android application that could recognize if the device is connected to a Network. If not, application display an AlertDialog and give the chance to the user to go to the device settings and open the wifi.
I have create a BroadcastReceiver for this job but i dont know how i can create an AlertDialog and give the option to the user to enable the the wifi.
Here is the code of BroadcastReceiver.
public class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
if (noConnectivity) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("You must have internet connection");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.create();
builder1.show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
}
Please note, the below code is just for your reference. You could update/change this code based on your requirement.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private BroadcastReceiver mNetworkReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerNetworkBroadcastForNougat();
}
private void registerNetworkBroadcastForNougat() {
mNetworkReceiver = new NetworkChangeReceiver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
try
{
if (!isOnline(context)) {
showDialog(context);
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void showDialog(final Context context) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("You must have internet connection");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.create();
builder1.show();
}
private boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
}
My DeviceList.java code is as below :-
import com.technomentis.led.R;
public class DeviceList extends ActionBarActivity
{
//widgets
Button btnPaired;
ListView devicelist;
//Bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
//Calling widgets
btnPaired = (Button)findViewById(R.id.btnOn);
devicelist = (ListView)findViewById(R.id.listView);
//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
pairedDevicesList();
}
});
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, ledControl.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
startActivity(i);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_device_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My ledcontrol.java is as follow
package com.technomentis.led;
public class ledControl extends ActionBarActivity {
Button btnOn, btnOff, btnDis;
SeekBar brightness;
TextView lumn;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgtes
btnOn = (Button)findViewById(R.id.button2);
btnOff = (Button)findViewById(R.id.button3);
btnDis = (Button)findViewById(R.id.button4);
brightness = (SeekBar)findViewById(R.id.seekBar);
lumn = (TextView)findViewById(R.id.lumn);
new ConnectBT().execute(); //Call the class to connect
//commands to be sent to bluetooth
btnOn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
btnDis.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser==true)
{
lumn.setText(String.valueOf(progress));
try
{
btSocket.getOutputStream().write(String.valueOf(progress).getBytes());
}
catch (IOException e)
{
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TF".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TO".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_led_control, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
My ongoing R.java is as below
package com.technomentis.led;
public final class R {
public static final class attr {
}
public static final class mipmap {
public static final int cxemnet_logo=0x7f020000;
public static final int ic_action_search=0x7f020001;
public static final int ic_launcher=0x7f020002;
}
public static final class id {
public static final int btnOff=0x7f060000;
public static final int btnOn=0x7f060001;
public static final int listView=0x7f060002;
}
public static final class layout {
public static final int activity_device_list=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int btn_OFF=0x7f040003;
public static final int btn_ON=0x7f040002;
public static final int title_activity_main=0x7f040001;
}
public static final class style {
public static final int AppTheme=0x7f050000;
}
}
Can anybody help me in creating complete R.java file. I am unable to complete it.
Btw I am new to android studio.
I encounter this issue periodically. Build -> Rebuild Project and Build -> Clean Project always take care of the problem for me.
Thanks everyone,
Done with this problem. Simply create new project and copy pasted all files.
Rebuild done all the work.
Now need help in
Error:(53, 43) error: cannot find symbol variable lumn
I need to open the url inside the webview not the browser yet it always opens it in the browser Any reason why? I;ve added code to the WebView which I thought would do it. It has been working fine and now it opens in the browser for some reason
WebView Code:
public class MapActivity extends MenuActivity {
private final static String TAG = "HearingTest";
private WebView webView;
private String urlString;
private ProgressDialog progressDialog;
private Context context = MapActivity.this;
private boolean isPageLoadedComplete = false;
private Timer myTimer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
ActivityHelper activityHelper = new ActivityHelper(this);
activityHelper.setTitleTextSize(R.string.Store_Locator, false);
urlString = getString(R.string.location_url);
WebViewSettings();
LoadWebPage(urlString);
}
public void LoadWebPage(String url){
try {
webView.loadUrl(url);
Log.d(TAG, "URL" + url + "connected");
}
catch (Exception e) {
Log.d(TAG, "URL: " + url + " couldn't connect.");
}
}
public void WebViewSettings(){
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.canGoBack();
Uri uri = Uri.parse(urlString);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
myTimer = new Timer();
//Start this timer when you create you task
myTimer.schedule(new loaderTask(), 20000);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals(urlString)) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
#Override
public void onLoadResource(WebView view, String url) {
// Check to see if there is a progress dialog
if (progressDialog == null) {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Please wait.");
progressDialog.setCancelable(true);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
}
#Override
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
#Override
public void onPageFinished(WebView view, String url) {
isPageLoadedComplete = true;
View mapHeight = (View) findViewById(R.id.webview);
int height = mapHeight.getHeight();
Log.d("map height","map height" + height);
// Page is done loading;
// hide the progress dialog and show the webview
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
#Override
public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
AlertDialog();
}
});
}
public class loaderTask extends TimerTask {
public void run() {
System.out.println("Times Up");
if(isPageLoadedComplete){
Log.d(TAG, "The page loaded perfectly");
myTimer.cancel();
}else{
Log.d(TAG, "The page was not loaded correctly");
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception e) {
e.printStackTrace();
}
runOnUiThread(new Runnable()
{
public void run()
{
AlertDialog();
}
});
}
}
}
public void AlertDialog(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(R.string.Search_Error);
alertDialog.setMessage(R.string.Failure_to_create_URL_connection);
alertDialog.setNeutralButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
}Fsie
I want to send an sms if i click the alert box button.I have an listview with checkbox after clicking the checkbox,above i put an buttonselected,After click that button it shows one alert box which contains the selected things with "ok" alertsetbutton.What i need is after clicking the ok button,i have to send an sms and an email with the selected content.
How can i do this.
Main activity.java
public class MainActivity extends Activity implements FetchDataListener,OnClickListener
{
private static final int ACTIVITY_CREATE=0;
private ProgressDialog dialog;
ListView lv;
private List<Application> items;
private Button btnGetSelected;
//private ProjectsDbAdapter mDbHelper;
//private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
//mDbHelper = new ProjectsDbAdapter(this);
//mDbHelper.open();
//fillData();
//registerForContextMenu(getListView());
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
initView();
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://dry-brushlands-3645.herokuapp.com/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
//mDbHelper.open();
//Cursor projectsCursor = mDbHelper.fetchAllProjects();
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
//String[] from = new String[]{ProjectsDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
//int[] to = new int[]{R.id.text1};
/* Now create a simple cursor adapter and set it to display
SimpleCursorAdapter projects =
new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
setListAdapter(projects);
*/
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
/*dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, ProjectEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data)
{
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
StringBuffer sb = new StringBuffer();
// Retrive Data from list
for (Application bean : items) {
if (bean.isSelected()) {
sb.append(Html.fromHtml(bean.getContent()));
sb.append(",");
}
}
showAlertView(sb.toString().trim());
}
#SuppressWarnings("deprecation")
private void showAlertView(String str) {
AlertDialog alert = new AlertDialog.Builder(this).create();
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
String strContactList = str.substring(0, str.length() - 1);
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
}
});
/*buttonSendSms_intent.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String smsNumber = edittextSmsNumber.getText().toString();
String smsText = edittextSmsText.getText().toString();
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
}});*/
alert.show();
}
#Override
public void onBackPressed() {
AlertDialog alert_back = new AlertDialog.Builder(this).create();
alert_back.setTitle("Quit?");
alert_back.setMessage("Are you sure want to Quit?");
alert_back.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert_back.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
});
alert_back.show();
}
#Override
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
// TODO Auto-generated method stub
}
}
Here alert.setbutton is the crucial button,from there only i need,I already put sms code its not working properly.
Here i add my asynctask also.
public class FetchDataTask extends AsyncTask<String, Void, String>
{
private final FetchDataListener listener;
private String msg;
public FetchDataTask(FetchDataListener listener)
{
this.listener = listener;
}
#Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("post");
// create apps list
List<Application> apps = new ArrayList<Application>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setContent(json.getString("content"));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ( (line = reader.readLine()) != null )
{
sb.append(line + "\n");
}
}
catch ( IOException e )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
call this method from your button clicking event.
sendSMS("Any text like your name","Your number","Your sms text");
method :
public static void sendSMS(String status, String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
Also declare this permission in your manifest :
<uses-permission android:name="android.permission.SEND_SMS"/>
Simple.
Put this in the click listener for the OK Button
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
I cant figure out why i cant set text to my textView tv.
getting:
E/AndroidRuntime(686): android.view.ViewRoot$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
I tried many ways to make it right.
As you can see i tried Handler because i had the same problem with toasts. Now toast works but setText doesnt :((
Please someone help me, how should i configure this handler?
public class calculate extends Activity implements OnClickListener {
private myService myService; //bound service instance
private boolean serviceStarted;
View show_map;
View data;
View start;
View stop;
public TextView tv;
private Location loc;
private boolean initiated=false;
private float distance=0;
UIHandler uiHandler;
route_calc rc;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.calculate);
tv=(TextView)findViewById(R.id.textView1);
show_map=findViewById(R.id.button1);
show_map.setOnClickListener(this);
data=findViewById(R.id.button2);
data.setOnClickListener(this);
start=findViewById(R.id.button3);
start.setOnClickListener(this);
stop=findViewById(R.id.button4);
stop.setVisibility(View.INVISIBLE);
stop.setOnClickListener(this);
HandlerThread uiThread = new HandlerThread("UIHandler");
uiThread.start();
uiHandler = new UIHandler( uiThread.getLooper());
}
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View v) {
Intent i;
switch(v.getId()){
case R.id.button1:
i=new Intent(this,Map.class);
startActivity(i);
break;
case R.id.button2:
i=new Intent(this,data.class);
startActivity(i);
break;
case R.id.button3:
startService();
break;
case R.id.button4:
stopService();
break;
}
}
//connection between this activity and service myService
ServiceConnection myServConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName arg0) {
myService = null;
}
#Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
myService = ((myService.MyBinder)binder).getMyService();
}
};
private void startService() {
Intent intent = new Intent(this, myService.class);
startService(intent);
//Bind MyService here
bindService(intent, myServConn, BIND_AUTO_CREATE);
stop.setVisibility(View.VISIBLE);
serviceStarted = true;
rc = new route_calc();
rc.start();
}
private void stopService() {
if(serviceStarted) {
Intent intent = new Intent(this, myService.class);
//Unbind MyService here
unbindService(myServConn);
stopService(intent);
stop.setVisibility(View.INVISIBLE);
serviceStarted = false;
}
}
void showToast(String s){
handleUIRequest(s);
}
void setText(){
handleUISetText();
}
class route_calc extends Thread{
Location begin;
public void run() {
float temp;
while(!initiated){
try{
loc=myService.getLocation();
}
catch(Exception e){
}
if(loc!=null){
begin=loc;
initiated=true;
showToast("zadzialalo");
}
}
while(true){
loc=myService.getLocation();
temp=begin.distanceTo(loc);
distance=distance+temp;
tv.setText("przejechales "+distance+" m");
System.err.println(distance);
begin=loc;
try {
this.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private final class UIHandler extends Handler
{
public static final int DISPLAY_UI_TOAST = 0;
public static final int TV_SET_TEXT = 1;
public UIHandler(Looper looper)
{
super(looper);
}
public void handleMessage(Message msg)
{
switch(msg.what)
{
case UIHandler.DISPLAY_UI_TOAST:
{
Context context = getApplicationContext();
Toast t = Toast.makeText(context, (String)msg.obj, Toast.LENGTH_LONG);
t.show();
}
case UIHandler.TV_SET_TEXT:
{
tv.setText("przejechałeś "+distance+" m");
}
default:
break;
}
}
}
protected void handleUIRequest(String message)
{
Message msg = uiHandler.obtainMessage(UIHandler.DISPLAY_UI_TOAST);
msg.obj = message;
uiHandler.sendMessage(msg);
}
protected void handleUISetText(){
Message msg=uiHandler.obtainMessage(UIHandler.TV_SET_TEXT);
uiHandler.sendMessage(msg);
}
}
It seems like you put your entire Activity here, and that it also includes a service, and you didn't try to narrow down your problem.
in your route_calc thread you call showToast, this is probably one of your problems, you should call showToast (or any other UI function) from your Handler.
Something like this:
Do anything you want on your thread:
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
someHeavyStuffHere(); //Big calculations or file download here.
handler.sendEmptyMessage(SUCCESS);
}
catch (Exception e)
{
handler.sendEmptyMessage(FAILURE);
}
}
}).start();
When your data is ready, tell the handler to put it in a view and show it:
protected Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == SUCCESS)
{
setCalculatedDataToaView(); // the data you calculated from your thread can now be shown in one of your views.
}
else if (msg.what == FAILURE)
{
errorHandlerHere();//could be your toasts or any other error handling...
}
}
};