[Q] Create notification when bluetooth data is received in the background - Java for Android App Development

I am currently working on an arduino project that connects to my phone using a bluetooth module.
On the arduino I have various diagnostic sensors hooked up to it. When the sensors "sense an error," I would like to receive a notification on my phone.
I'm guessing this would require me to program an app that runs as a background service listening for data coming across the bluetooth connection. Then when it receives the data it would need to create a notification and play the system notification sound.
Is it even possible to listen to the data coming from the bluetooth module while being run in the background?
How hard would this be for me, a beginner, to program? I have programmed in several other languages (html, visual basic, and python), so I understand basic coding concepts.

I would like to thank everyone for all the help. The amount of replies just shows how useful this forum is to beginning devs.
Anyways, after three days of straight research, I pumped out a working app. Now I would like for someone to review my code and see if anything can be revised or done better, as I really don't know what I'm doing.
The main activity:
Code:
package com.example.bluetooth;
//Import needed files
import java.util.ArrayList;
import java.util.Set;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
//Main activity class
public class MainActivity extends ActionBarActivity {
//Creates object variables
private Button list, disconnect;
private ListView lv;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
private Toast toast;
@Override
//on create
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creates variables containing id's
list = (Button) findViewById(R.id.button1);
disconnect = (Button) findViewById(R.id.button2);
lv = (ListView) findViewById(R.id.listView1);
//When you click the list item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object obj = lv.getAdapter().getItem(position);
String str = obj.toString();
int strStartIndex = str.indexOf("\n");
str = str.substring(strStartIndex + 1);
//check to see if bluetooth is enabled before
//starting the service
if (BA.isEnabled()) {
toast = Toast.makeText(getApplicationContext(),
"Connecting to: " + str, Toast.LENGTH_SHORT);
toast.show();
//connects to item you tapped, creating a service
Intent btConnectIntent = new Intent(MainActivity.this, ForegroundService.class);
btConnectIntent.setAction("btConnect");
btConnectIntent.putExtra("mac", str);
startService(btConnectIntent);
}
//Bluetooth isn't enabled
else{
toast = Toast.makeText(getApplicationContext(),
"Bluetooth must be enabled!", Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
//When you click the list button
public void list(View view) {
//Get bluetooth adapter and set it to BA
BA = BluetoothAdapter.getDefaultAdapter();
//Make sure device has bluetooth
if (BA != null) {
//See if bluetooth is enabled and if it is, get the list of paired devices
if (BA.isEnabled()) {
bluetoothList();
}
//If bluetooth isn't enabled, enable it
else {
//Start new intent to see if they turn on bluetooth
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
toast = Toast.makeText(getApplicationContext(),
"Bluetooth must be on!", Toast.LENGTH_SHORT);
toast.show();
}
}
//Device doesn't have a bluetooth adapter
else {
toast = Toast.makeText(getApplicationContext(),
"Your device doesn't support bluetooth!", Toast.LENGTH_SHORT);
toast.show();
}
}
//Waiting to see if they turn on bluetooth
//If they do, show list
public void onActivityResult(int requestCode, int resultCode, Intent turnOn) {
//if it turned on successfully, get the list of paired bluetooth devices
if (resultCode == RESULT_OK) {
bluetoothList();
}
}
//When they click disconnect button, stop the service
public void disconnect(View view) {
Intent stopIntent = new Intent(MainActivity.this, ForegroundService.class);
stopIntent.setAction("stopForeground");
startService(stopIntent);
}
//Method that gets the list of paired devices
private void bluetoothList() {
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for (BluetoothDevice bt : pairedDevices)
list.add(bt.getName() + "\n" + bt.getAddress());
//create array adapter
final ArrayAdapter adapter = new ArrayAdapter
(this, android.R.layout.simple_list_item_1, list);
//connect our list view to the adapter
lv.setAdapter(adapter);
toast = Toast.makeText(getApplicationContext(),
"Showing paired devices", Toast.LENGTH_SHORT);
toast.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_main, menu);
return true;
}
}
And the foreground service:
Code:
package com.example.bluetooth;
//Import needed files
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
//Service class
public class ForegroundService extends Service {
int FOREGROUND_ID = 1997;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter BA;
private BluetoothSocket BS;
private StringBuilder sb = new StringBuilder();
private Toast toast;
private String mac;
private Handler h;
//When the service is created
//Doesn't run again unless service is totally killed
public void onCreate() {
//Set service as foreground service
startForeground(FOREGROUND_ID, buildForegroundNotification());
toast = Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_SHORT);
toast.show();
//Get bluetooth adapter and set it to BA
BA = BluetoothAdapter.getDefaultAdapter();
//Create a handler to listen for data
//New threads send data to this handler
//If it receives data, show it in a toast
h = new Handler() {
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
toast = Toast.makeText(getApplicationContext(), bundle.getString("str"), Toast.LENGTH_SHORT);
toast.show();
}
;
};
}
//Called every time an activity runs startService
public int onStartCommand(Intent intent, int flags, int startId) {
//When an activity starts the service, it sends an action
//Check if action = btConnect
if (intent.getAction().equals("btConnect")) {
//Make sure there's not already an open socket
if (BS == null) {
//Creates a bundle to get data
Bundle extras = intent.getExtras();
//Extracts data from bundle, in this case the mac address
mac = extras.getString("mac");
//Creates another handler to listen for data
final Handler mHandler = new Handler();
//A runnable called when can't connect
final Runnable hUnsuccessful = new Runnable() {
public void run() {
toast = Toast.makeText(getApplicationContext(),
"Unsuccessful", Toast.LENGTH_SHORT);
toast.show();
toast = Toast.makeText(getApplicationContext(), "Service stopped", Toast.LENGTH_SHORT);
toast.show();
//Kill the service
stopForeground(true);
stopSelf();
}
};
//A runnable called when successfully connected
final Runnable hSuccessful = new Runnable() {
public void run() {
//Run method using socket BS
//Method listens for data coming across socket
ConnectedThread(BS);
toast = Toast.makeText(getApplicationContext(),
"Successful", Toast.LENGTH_SHORT);
toast.show();
}
};
//Creates a new thread since BS.connect
//will block the main thread otherwise
Thread thread = new Thread() {
public void run() {
//Creates BluetoothDevice from the mac address
//mac address was passed to service in onStartCommand
BluetoothDevice device = BA.getRemoteDevice(mac);
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
BS = device.createRfcommSocketToServiceRecord(MY_UUID);
}
//If it can't create a socket
catch (IOException e) {
//Send unsuccessful to the handler
mHandler.post(hUnsuccessful);
return;
}
// Cancel discovery because it will slow down the connection
BA.cancelDiscovery();
//Try to connect
try {
BS.connect();
}
// Unable to connect, send a toast and close the socket
catch (IOException connectException) {
//Try to close socket
try {
if (BS != null) {
BS.close();
BS = null;
}
//Send unsuccessful to the handler
mHandler.post(hUnsuccessful);
return;
}
//Can't close socket, do nothing
catch (IOException closeException) {
}
}
//If it made it to here, it was successful
//Send successful to the handler
mHandler.post(hSuccessful);
}
};
//Start the thread
thread.start();
}
//if BS != null
//Currently connected to a socket
else {
toast = Toast.makeText(getApplicationContext(), "You must disconnect first", Toast.LENGTH_SHORT);
toast.show();
}
}
//When an activity starts the service, it sends an action
//Check if action = stopForeground
if (intent.getAction().equals("stopForeground")) {
toast = Toast.makeText(getApplicationContext(), "Service stopped", Toast.LENGTH_SHORT);
toast.show();
//Try to close socket if one is open
try {
if (BS != null) {
BS.close();
BS = null;
toast = Toast.makeText(getApplicationContext(),
"Bluetooth device disconnected", Toast.LENGTH_SHORT);
toast.show();
}
}
//If it can't close it, do nothing
catch (IOException e) {
}
//Kill the service
stopForeground(true);
stopSelf();
}
//Service should stay alive, unless we kill it
return START_STICKY;
}
//Method to create foreground notification
private Notification buildForegroundNotification() {
NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
notification.setOngoing(true);
notification.setContentTitle("Bluetooth Service")
.setContentText("Service to listen for bluetooth data")
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setPriority(Notification.PRIORITY_MIN);
return (notification.build());
}
//Method to create a notification
private void notification(String title, String text) {
int mId = 0;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setContentTitle(title)
.setContentText(text)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setPriority(NotificationCompat.PRIORITY_MAX);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
}
//Looping method to listen for data over bluetooth socket
private void ConnectedThread(BluetoothSocket socket) {
final InputStream mmInStream;
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
//Create new thread as it will otherwise block main thread
Thread thread = new Thread() {
public void run() {
byte[] buffer = new byte[256]; //buffer store for the stream
int bytes; //bytes returned from read()
//Keep listening to the InputStream until an exception occurs
while (true) {
try {
Message msg = new Message();
Bundle bundle = new Bundle();
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
String strIncom = new String(buffer, 0, bytes);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
bundle.putString("str", sbprint);
msg.setData(bundle);
h.sendMessage(msg);
notification("Sensor Data:", sbprint);
}
}
//If InputStream gets interrupted
catch (IOException e) {
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("str", "Lost connection");
msg.setData(bundle);
h.sendMessage(msg);
notification("Error", "Lost connection");
Intent stopIntent = new Intent(getApplicationContext(), ForegroundService.class);
stopIntent.setAction("stopForeground");
startService(stopIntent);
break;
}
}
}
};
//Start the thread
thread.start();
}
//Required
public IBinder onBind(Intent intent) {
return null;
}
}

Related

[Q] remove proximityAlert after notification

what I am trying to do is have a proximity alert service which triggers a notification ONLY ONCE when you step inside the radius (without stopping the service). my code triggers notifications every time you step inside the radius and every time you step outside the radius. i've been trying with booleans and with removeProximityAlert, but no success. can anyone help?
Code:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class ProximityService extends Service {
private String PROX_ALERT_INTENT = "com.example.proximityalert";
private BroadcastReceiver locationReminderReceiver;
private LocationManager locationManager;
private PendingIntent proximityIntent;
[user=439709]@override[/user]
public void onCreate() {
locationReminderReceiver = new ProximityIntentReceiver();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
double lat = 55.586568;
double lng = 13.0459;
float radius = 1000;
long expiration = -1;
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
registerReceiver(locationReminderReceiver, filter);
Intent intent = new Intent(PROX_ALERT_INTENT);
intent.putExtra("alert", "Test Zone");
proximityIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
locationManager.addProximityAlert(lat, lng, radius, expiration, proximityIntent);
}
[user=439709]@override[/user]
public void onDestroy() {
Toast.makeText(this, "Proximity Service Stopped", Toast.LENGTH_LONG).show();
try {
unregisterReceiver(locationReminderReceiver);
} catch (IllegalArgumentException e) {
Log.d("receiver", e.toString());
}
}
[user=439709]@override[/user]
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Proximity Service Started", Toast.LENGTH_LONG).show();
}
[user=439709]@override[/user]
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public class ProximityIntentReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
[user=1299008]@supp[/user]ressWarnings("deprecation")
[user=439709]@override[/user]
public void onReceive(Context arg0, Intent arg1) {
String place = arg1.getExtras().getString("alert");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(arg0, 0, arg1, 0);
Notification notification = createNotification();
notification.setLatestEventInfo(arg0, "Entering Proximity!", "You are approaching a " + place + " marker.", pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
locationManager.removeProximityAlert(proximityIntent);
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
return notification;
}
}
}

Pass Connection Between Intents

I am building an android application to do various queries on my MySQL database. Once a successful login has returned on the main activity, I create a new Intent that holds search and query options. Here's the issue I am having. I keep getting a null pointer exception on stmt = con.createStatement(); Below is my logcat:
Code:
08-20 16:12:07.359 654-810/com.android.exchange D/ExchangeService: !!! deviceId unknown; stopping self and retrying
08-20 16:12:08.469 36-653/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: java.lang.NullPointerException
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.Networking.Search(Networking.java:44)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.ControlActivity$1.run(ControlActivity.java:53)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at java.lang.Thread.run(Thread.java:856)
08-20 16:12:12.369 654-654/com.android.exchange D/ExchangeService: !!! EAS ExchangeService, onStartCommand, startingUp = false, running = false
08-20 16:12:12.369 278-498/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
08-20 16:12:12.369 654-815/com.android.exchange D/ExchangeService: !!! Email application not found; stopping self
08-20 16:12:12.379 278-278/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
I'm curious whether it is better practice to close the connection and reopen it in the new intent? Or pass the connection between intents somehow?
Any input would be greatly appreciated!
wait...
Here are snippets of my code to help debug.
Code:
[user=439709]@override[/user]
public void onClick(View view) {
if(view.getId() == R.id.LoginButton) {
Toast.makeText(getApplicationContext(), "Attempting Connection", Toast.LENGTH_SHORT).show();
//Spawn new thread
new Thread(new Runnable() {
public void run() {
if(net.execLogin(mUserInput.getText().toString(), mPassInput.getText().toString())) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connected to Database", Toast.LENGTH_LONG).show();
}
});
//start new activity
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
[user=439709]@override[/user]
public void run() {
Intent intent = new Intent(LoginActivity.this, ControlActivity.class);
startActivity(intent);
}
});
}
else {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connection Failed :(", Toast.LENGTH_LONG).show();
}
});
}
}
}).start();
}
}
And here is the new activity started by the above code:
Code:
package com.example.testapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ControlActivity extends Activity implements View.OnClickListener {
private ArrayList<Hardware> list = new ArrayList<Hardware>();
EditText mEditText;
ListView mListView;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control);
setupPage();
}
public void setupPage() {
Button search = (Button)findViewById(R.id.search);
search.setOnClickListener(this);
mEditText = (EditText)findViewById(R.id.editText);
mListView = (ListView)findViewById(R.id.listView);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.control, menu);
return true;
}
public void onClick(View view) {
if(view.getId() == R.id.search) {
new Thread(new Runnable() {
public void run() {
list = new Networking().Search("Type", mEditText.getText().toString());
}
}).start();
ArrayAdapter<Hardware> adapter = new ArrayAdapter<Hardware>(this, android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
if(list == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "0 Results Yielded :(", Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
And here is the code I use to connect and query the database
Code:
import java.sql.*;
import java.util.*;
public class Networking implements DbQuery {
private static final String DRIVER = "org.mariadb.jdbc.Driver";
private static final String URL = "jdbc:mysql://146.187.16.32/Peirce";
ArrayList<Hardware> ara = new ArrayList<Hardware>();
Database db = new Database();
Hardware h1;
Connection con = null;
Statement stmt = null;
public boolean execLogin(String uName, String pWord) {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, uName, pWord);
if(!con.isClosed()){
return true;
}
return false;
}catch(SQLException e) {
e.printStackTrace();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
public ArrayList<Hardware> Search(String arg, String target) {
try {
stmt = con.createStatement(); //throws null pointer exception
ResultSet rs = stmt.executeQuery("Select * from " + db.getTable() + " where " + arg + "='" + target + "';");
while(rs.next()) {
ara.add(new Hardware(rs.getString("Type"), rs.getString("Make"), rs.getString("Model"), rs.getString("Serial"), rs.getString("Comments")));
}
return ara;
}catch(SQLException e) {
e.printStackTrace();
}catch(NullPointerException e) {
e.printStackTrace();
}
return ara;
}
nevermind
i have figured it out.

Accelerometer Data

I have the code below created but I can not for the life of me figure out how I can send data from the accelerator. I need it to send a constant stream of data until I turn it off. I can't even figure out how to cast the data to a proper variable. Any suggestion would be greatly appreciated.
Code:
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener
{
private static final String TAG = "bluetooth1";
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
Button on, off;
float values;
TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uuid = tManager.getDeviceId();
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private UUID MY_UUID = UUID
.fromString(uuid);
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "B0:C4:E7:CF:19:6E";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
acceleration = (TextView) findViewById(R.id.accelText);
off = (Button) findViewById(R.id.bOff);
on = (Button) findViewById(R.id.bOn);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
// On click Listeners
off.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
sendData("a");
Toast.makeText(getBaseContext(), "Turn on LED",
Toast.LENGTH_SHORT).show();
}
});
on.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
sendData("a");
Toast.makeText(getBaseContext(), "Turn on LED",
Toast.LENGTH_SHORT).show();
}
});
// End Onclick Listeners
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException
{
if (Build.VERSION.SDK_INT >= 10)
{
try
{
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e)
{
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@Override
public void onResume()
{
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try
{
btSocket = createBluetoothSocket(device);
} catch (IOException e1)
{
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try
{
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e)
{
try
{
btSocket.close();
} catch (IOException e2)
{
errorExit("Fatal Error",
"In onResume() and unable to close socket during connection failure"
+ e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try
{
outStream = btSocket.getOutputStream();
} catch (IOException e)
{
errorExit(
"Fatal Error",
"In onResume() and output stream creation failed:"
+ e.getMessage() + ".");
}
}
@Override
public void onPause()
{
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null)
{
try
{
outStream.flush();
} catch (IOException e)
{
errorExit(
"Fatal Error",
"In onPause() and failed to flush output stream: "
+ e.getMessage() + ".");
}
}
try
{
btSocket.close();
} catch (IOException e2)
{
errorExit("Fatal Error", "In onPause() and failed to close socket."
+ e2.getMessage() + ".");
}
}
private void checkBTState()
{
// Check for Bluetooth support and then check to make sure it is turned
// on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null)
{
errorExit("Fatal Error", "Bluetooth not supported");
} else
{
if (btAdapter.isEnabled())
{
Log.d(TAG, "...Bluetooth ON...");
} else
{
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message)
{
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message)
{
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try
{
outStream.write(msgBuffer);
} catch (IOException e)
{
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event)
{
// TODO Auto-generated method stub
acceleration.setText("x: " + event.values[0] + "\nY:" + event.values[1]
+ "\nZ:" + event.values[2]);
}
}
NoiseAgent said:
I can not for the life of me figure out how I can send data from the accelerator.
Click to expand...
Click to collapse
What's your exact problem? You're getting the data from the accelerator in the onSensorChanged()-Method, so you just need to send them there.
Reply
EmptinessFiller said:
What's your exact problem? You're getting the data from the accelerator in the onSensorChanged()-Method, so you just need to send them there.
Click to expand...
Click to collapse
My problem is I am unsure how to send it. How do you actually do that? I don't know what the syntax is to transmit data over bluetooth. The sendData wont work it gives me the error sendData(String) in the type MainActivity is not applicable for the arguments(Sensor)
Use DataOutputStream and DataInputStream to send/read the three float-values: DataOutputStream#writeFloat(event.values[0/1/2]);
EmptinessFiller said:
Use DataOutputStream and DataInputStream to send/read the three float-values: DataOutputStream#writeFloat(event.values[0/1/2]);
Click to expand...
Click to collapse
Sweet baby jesus, lord all mighty, thank you.
When I add that to the onSensorChanged I get the error "Cannot make a static reference to the non-static method writeFloat(float) from
the type DataOutputStream" not sure how to clear it up.
Also, I have jumped in way over my head, I really just want to wrap this last bit up and start from scratch. If anyone has a good resource for learning object oriented Java programming and would like to share, that would just be the bees-knees.
Of course java/object oriented programming is necessary.
You have to create an object from the ObjectOutputStream like
ObjectOutputStream oos = new ObjectOutputStream(...);
oos.writeFloat(...);
...

Updating tabs to new tab fragments

Hi all,
I had an app that was working about 3 years ago that I decided to update for the latest android sdk.I was using tabs but have decided to update to tab fragments with swipe.The problem I'm having is how to lay out the code.I have updated my app but have a few errors.Specifically the Book Now tab usually has a book now form so people can fill it out and upon clicking submit it sms's it to me.Below is the code for BookNowFragmnet.java.
I should mention that the tab and swipe part works flawlessly.I dont have a logcat because it wont build without removing the code
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String phoneNo = edittextPhone.getText().toString();
String message = editTextProblem.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The problem areas are as follows;
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
dfwcomputer said:
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
Click to expand...
Click to collapse
So you are asking for the method "getBaseContext" within an onClickListener... it does not have a method called that... like it's telling you it's undefined
It would probably be a better idea to use application context either by direct use of getApplicationContext or by a "final" reference maybe...
dfwcomputer said:
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
Click to expand...
Click to collapse
BookNowFragment is not extended from the base type of Context that is expected in the arguments.
dfwcomputer said:
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
Click to expand...
Click to collapse
dfwcomputer said:
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
Click to expand...
Click to collapse
Actually the last to are just repeats of the previous really... I'm guessing here but it seems you may have skipped ahead of where you should be in a learning sense.. cause it seems to be like your running without being knowing how to jog kinda thing. Not attempting to be condescending, just I'm a trainer and always attempt to point this stuff out when I see it
Maybe go back and do some of the basics again, and include fragments etc
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
dfwcomputer said:
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
Click to expand...
Click to collapse
hmmm, well if thats all thats wrong with it, all I could offer is for you to send me the packaged src+res and I will have a look... if it takes less than 20 min to fix and get running I have no problem fixing it for you. If it doesn't and maybe takes longer then I may have to leave it. Should be quick though, up to you
But with the info I gave you should be able to fix those 4 issues...if not hit me up on hangouts and will talk you though it
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
dfwcomputer said:
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
Click to expand...
Click to collapse
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
deanwray said:
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
Click to expand...
Click to collapse
lol now I have less faith ill be fixing it..... Ill let you know thanks again
sent you a private message m8, because there is some personal info in the app
dfwcomputer said:
sent you a private message m8, because there is some personal info in the app
Click to expand...
Click to collapse
fixed and sent private msg with class
Thanks again, I apreciate it.I have changed the personal info and posted the working code here incase someone else has a similar issue.
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
//edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
//editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String strPhoneNo = "0000000000";
TextView txtName = (TextView) rootView.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView.findViewById(R.id.edittextPhone);
TextView txtProblem = (TextView) rootView.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n"
+ strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I forgot the date and time picker arrrrrrrgh
I've added the following 2 classes which have no errors and seem to function fine.
DatePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
TextView txtDate;
public DatePickerFragment(TextView txtDate) {
super();
this.txtDate = txtDate;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
txtDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
}
TimePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
TextView txtTime;
public TimePickerFragment(TextView txtTime) {
super();
this.txtTime = txtTime;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
txtTime.setText(hourOfDay+":"+minute);
}
}
I then updated BookNowFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
Button btnChangeDate,btnChangeTime;
TextView txtDisplayDate,txtDisplayTime;
DatePicker datePicker;
TimePicker timePicker;
private int year;
private int month;
private int day;
private int hour;
private int minute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow,
container, false);
showCurrentDateOnView();
showCurrentTimeOnView();
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
// edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
// editTextProblem = (EditText)
// rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strPhoneNo = "00000000";
TextView txtName = (TextView) rootView
.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView
.findViewById(R.id.edittextPhone);
//TextView txtDate = (TextView) rootView.findViewById(R.id.date);
TextView txtProblem = (TextView) rootView
.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
//String strDate = "Date: " + txtDate.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n" + strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0,
new Intent(SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
// display current date
public void showCurrentDateOnView() {
txtDisplayDate = (TextView) findViewById(R.id.txtDate);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
txtDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// set current date into datepicker
datePicker.init(year, month, day, null);
}
// display current time
public void showCurrentTimeOnView() {
txtDisplayTime = (TextView) findViewById(R.id.txtTime);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
txtDisplayTime.setText(
new StringBuilder().append(hour)
.append(":").append(minute));
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment(txtDisplayDate);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment(txtDisplayTime);
newFragment.show(getSupportFragmentManager(), "timePicker");
}
@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);
return true;
}
}
The problem areas are all under BookNowFragment.java;
1. Under "showCurrentDateOnView" the both findViewById says undefined for the type.I have tried adding rootView but didnt work.
2. Under "showCurrentTimeOnView" both findViewById says undefined for the type.I have tried adding rootView but didnt work.
3. under "showDatePickerDialog" and "showTimePickerDialog" both the getSupportFragmentManager methods show the error "The method getSupportFragmentManager() is undefined for the type BookNowFragment"
4. I also have errors with "onCreateOptionsMenu".I worked out some of them by adding getActivity (see new code below) but it still shows the error "The method onCreateOptionsMenu(Menu) of type BookNowFragment must override or implement a supertype method"
PHP:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Think there simple issues although I'm simple as well so I could be understating it.

[Q] Code placement for writing TCP/IP data to TextView

Hello,
I am a first time poster new to Android app development so please bear with me. I am currently working off of two great TCP/IP Client examples. My goal is to create a simple TCP/IP Client that connects to a server and, once a connection is established, continuously updates a TextView with strings passed from the server. If the user presses a button, the client sends a stop command to the server and I would ultimately like to expand the TextView into a graph with the converted string values. I am able to establish the connection to the server and send the stop command from the client but my attempts at adding the read capability have, so far, been unsuccessful with the app crashing as soon as it starts up.
Since it is my first time posting, I am not allowed to link the examples I am using. If anyone is interested in seeing them, however, they are posts from the android-er blog titled: "Android Server/Client example - client side using Socket" and "Bi-directional communication between Client and Server, using ServerSocket, Socket, DataInputStream and DataOutputStream".
Here is the code in my MainActivity:
Code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textResponse;
TextView textIn;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonStopTest, buttonDisconnect;
Socket socket = null;
DataInputStream incomingString = null;
DataOutputStream terminalLetter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonDisconnect = (Button)findViewById(R.id.disconnect);
buttonStopTest = (Button)findViewById(R.id.stop_test);
textResponse = (TextView)findViewById(R.id.response);
textIn = (TextView)findViewById(R.id.text_in);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonStopTest.setOnClickListener(buttonStopTestOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
//Clicking button (Connect) calls a MyClientTask defined below.
MyClientTask myClientTask = new
MyClientTask(editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}
};
OnClickListener buttonStopTestOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
terminalLetter = new DataOutputStream(socket.getOutputStream());
terminalLetter.writeByte('b');
terminalLetter.writeByte('\n');
terminalLetter.close();
socket.close();
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection.");
}
}
};
OnClickListener buttonDisconnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String IPaddress;
int Port;
String response = "";
MyClientTask(String addr, int port){
IPaddress = addr;
Port = port;
}
@Override
protected Void doInBackground(Void... arg0) {
//Took socket declaration from here.
try {
//Taking relevant parameters and applying them to socket
socket = new Socket(IPaddress, Port);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
incomingString = new DataInputStream(socket.getInputStream());
textIn.setText(incomingString.readUTF());
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I put the commands for reading data from the server and writing it to the TextView with the code that sets up the connection to the socket. The idea was that it would be the next step after the connection is established but I realize that it looks like I am only reading once. I tried adding a while loop and bringing it out of the doInBackground. In each case, all I got was the whole app crashing on me. It looks fairly straight forward in the example but there the connection is automatic, not triggered and I have not been able to modify the code successfully.
I am still new to Android and this feels like it is an important part of app development so I am hoping someone in the community can help me understand where the section of code relevant to reading data (continuously) should be placed in relation to the rest.
Best,
Yusif Nurizade
P.S. I was going to include the fragment but, since the post is long enough, I chose to omit it. I can share upon request and the logcat.

Categories

Resources