EMDK Serial Communication Finds No Ports - android

I am trying to create an Android activity which sends data through the serial port as a product test. I have some code for doing so, which, so far, finds no serial ports on my device which definitely has a serial port. I intend to use this activity with a loopback connector on the serial port of the device to verify both the read and write functionalities. I have tried these two programs:
import android.app.Activity;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKManager.EMDKListener;
import com.symbol.emdk.EMDKManager.FEATURE_TYPE;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.serialcomm.SerialComm;
import com.symbol.emdk.serialcomm.SerialCommException;
import com.symbol.emdk.serialcomm.SerialCommManager;
import com.symbol.emdk.serialcomm.SerialCommResults;
import com.symbol.emdk.serialcomm.SerialPortInfo;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
import java.util.List;
public class SerialTry3 extends Activity implements EMDKListener{
private String TAG = SerialTry3.class.getSimpleName();
private EMDKManager emdkManager = null;
private SerialComm serialCommPort = null;
private SerialCommManager serialCommManager = null;
private EditText txtDataToSend = null;
private TextView txtStatus = null;
private Button btnRead = null;
private Button btnWrite = null;
private Spinner spinnerPorts = null;
public HashMap<String, SerialPortInfo> supportedPorts = null;
#Override #SuppressWarnings("SetTextI18n")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serial_try);
txtDataToSend = (EditText) findViewById(R.id.txtDataToSend);
txtDataToSend.setText("Serial Communication Write Data Testing.");
spinnerPorts = (Spinner)findViewById(R.id.spinnerPorts);
btnWrite = (Button) findViewById(R.id.btnWrite);
btnRead = (Button) findViewById(R.id.btnRead);
txtStatus = (TextView) findViewById(R.id.statusView);
txtStatus.setText("");
txtStatus.requestFocus();
EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
new AsyncStatusUpdate().execute("EMDKManager object request failed!");
}
new AsyncUiControlUpdate().execute(false);
}
#Override
public void onOpened(EMDKManager emdkManager) {
this.emdkManager = emdkManager;
Log.d(TAG, "EMDK opened");
try{
serialCommManager = (SerialCommManager) this.emdkManager.getInstance(FEATURE_TYPE.SERIALCOMM_EX);
if(serialCommManager != null) {
populatePorts();
}
else
{
new AsyncStatusUpdate().execute(FEATURE_TYPE.SERIALCOMM_EX.toString() + " Feature not supported.");
}
}
catch(Exception e)
{
Log.d(TAG, e.getMessage());
new AsyncStatusUpdate().execute(e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash_main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
deinitSerialComm();
if (emdkManager != null) {
emdkManager.release();
emdkManager = null;
}
}
#Override
protected void onPause()
{
super.onPause();
deinitSerialComm();
serialCommManager = null;
supportedPorts = null;
// Release the serialComm manager resources
if (emdkManager != null) {
emdkManager.release(FEATURE_TYPE.SERIALCOMM_EX);
}
}
#Override
protected void onResume()
{
super.onResume();
// Acquire the serialComm manager resources
if (emdkManager != null) {
serialCommManager = (SerialCommManager) emdkManager.getInstance(FEATURE_TYPE.SERIALCOMM_EX);
if (serialCommManager != null) {
populatePorts();
if (supportedPorts != null)
initSerialComm();
}
}
}
void populatePorts()
{
try {
if(serialCommManager != null) {
List<SerialPortInfo> serialPorts = serialCommManager.getSupportedPorts();
if(serialPorts.size()>0) {
supportedPorts = new HashMap<String, SerialPortInfo> ();
String[] ports = new String[serialPorts.size()];
int count = 0;
for (SerialPortInfo info : serialPorts) {
supportedPorts.put(info.getFriendlyName(), info);
ports[count] = info.getFriendlyName();
count++;
}
spinnerPorts.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, ports));
spinnerPorts.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Disabling previous serial port before getting the new one
deinitSerialComm();
initSerialComm();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
else
{
new AsyncStatusUpdate().execute("Failed to get available ports");
Toast.makeText(this, "Failed to get available ports, serial communication may not be supported.", Toast.LENGTH_LONG).show();
finish();
}
}
else
{
new AsyncStatusUpdate().execute("SerialCommManager is null");
}
}
catch (Exception ex)
{
Log.d(TAG, ex.getMessage());
new AsyncStatusUpdate().execute(ex.getMessage());
}
}
void initSerialComm() {
new AsyncEnableSerialComm().execute(supportedPorts.get(spinnerPorts.getSelectedItem()));
}
#Override
public void onClosed() {
if(emdkManager != null) {
emdkManager.release();
}
new AsyncStatusUpdate().execute("EMDK closed unexpectedly! Please close and restart the application.");
}
public void btnReadOnClick(View arg)
{
new AsyncReadData().execute();
}
public void btnWriteOnClick(View arg)
{
new AsyncUiControlUpdate().execute(false);
try {
String writeData = txtDataToSend.getText().toString();
int bytesWritten = serialCommPort.write(writeData.getBytes(), writeData.getBytes().length);
new AsyncStatusUpdate().execute("Bytes written: "+ bytesWritten);
} catch (SerialCommException e) {
new AsyncStatusUpdate().execute("write: "+ e.getResult().getDescription());
}
catch (Exception e) {
new AsyncStatusUpdate().execute("write: "+ e.getMessage() + "\n");
}
new AsyncUiControlUpdate().execute(true);
}
void deinitSerialComm() {
if (serialCommPort != null) {
try {
serialCommPort.disable();
serialCommPort = null;
} catch (Exception ex) {
Log.d(TAG, "deinitSerialComm disable Exception: " + ex.getMessage());
}
}
}
#SuppressWarnings("StaticFieldLeak")
private class AsyncStatusUpdate extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return params[0];
}
#Override
protected void onPostExecute(String result) {
txtStatus.setText(result);
}
}
#SuppressWarnings("StaticFieldLeak")
private class AsyncUiControlUpdate extends AsyncTask<Boolean, Void, Boolean> {
#Override
protected Boolean doInBackground(Boolean... arg0) {
return arg0[0];
}
#Override
protected void onPostExecute(Boolean bEnable) {
btnRead.setEnabled(bEnable);
btnWrite.setEnabled(bEnable);
txtDataToSend.setEnabled(bEnable);
spinnerPorts.setEnabled(bEnable);
}
}
#SuppressWarnings("StaticFieldLeak")
private class AsyncEnableSerialComm extends AsyncTask<SerialPortInfo, Void, SerialCommResults>
{
#Override
protected SerialCommResults doInBackground(SerialPortInfo... params) {
SerialCommResults returnvar = SerialCommResults.FAILURE;
try {
serialCommPort = serialCommManager.getPort(params[0]);
} catch (Exception ex) {
ex.printStackTrace();
}
if (serialCommPort != null) {
try {
serialCommPort.enable();
returnvar = SerialCommResults.SUCCESS;
} catch (SerialCommException e) {
Log.d(TAG, e.getMessage());
e.printStackTrace();
returnvar = e.getResult();
}
}
return returnvar;
}
#Override #SuppressWarnings("SetTextI18n")
protected void onPostExecute(SerialCommResults result) {
super.onPostExecute(result);
if (result == SerialCommResults.SUCCESS) {
new AsyncStatusUpdate().execute("Serial comm channel enabled: (" + spinnerPorts.getSelectedItem().toString() + ")");
txtDataToSend.setText("Serial Communication Write Data Testing " + spinnerPorts.getSelectedItem().toString() + ".");
new AsyncUiControlUpdate().execute(true);
} else {
new AsyncStatusUpdate().execute(result.getDescription());
new AsyncUiControlUpdate().execute(false);
}
}
}
#SuppressWarnings("StaticFieldLeak")
private class AsyncReadData extends AsyncTask<Void, Void, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
new AsyncUiControlUpdate().execute(false);
new AsyncStatusUpdate().execute("Reading..");
}
#Override
protected String doInBackground(Void... params) {
String statusText = "";
try {
byte[] readBuffer = serialCommPort.read(10000); //Timeout after 10 seconds
if (readBuffer != null) {
String tempString = new String(readBuffer);
statusText = "Data Read:\n" + tempString;
} else {
statusText = "No Data Available";
}
} catch (SerialCommException e) {
statusText = "read:" + e.getResult().getDescription();
} catch (Exception e) {
statusText = "read:" + e.getMessage();
}
return statusText;
}
#Override
protected void onPostExecute(String statusText) {
super.onPostExecute(statusText);
new AsyncUiControlUpdate().execute(true);
new AsyncStatusUpdate().execute(statusText);
}
}
}
and
import android.app.Activity;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKManager.FEATURE_TYPE;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.serialcomm.SerialComm;
import com.symbol.emdk.serialcomm.SerialCommException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.symbol.emdk.serialcomm.SerialCommManager;
import com.symbol.emdk.serialcomm.SerialPortInfo;
import java.util.List;
public class SerialTry extends Activity implements EMDKManager.EMDKListener {
private String TAG = SerialTry.class.getSimpleName();
private EMDKManager emdkManager = null;
private SerialComm serialComm = null;
private SerialCommManager serialCommMan = null;
private EditText editText = null;
private TextView statusView = null;
private Button readButton = null;
private Button writeButton = null;
#Override #SuppressWarnings("SetTextI18n")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serial_try);
editText = (EditText) findViewById(R.id.editText1);
editText.setText("Serial Communication Write Data Testing.");
statusView = (TextView) findViewById(R.id.statusView);
statusView.setText("");
statusView.requestFocus();
EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
statusView.setText("Failed to open EMDK");
} else {
statusView.setText("Opening EMDK...");
}
//
// Get the serialComm/port object by passing a SerialPortInfo object:
addReadButtonEvents();
writeButtonEvents();
setEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash_main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (emdkManager != null) {
emdkManager.release();
emdkManager = null;
}
}
#Override
public void onOpened(EMDKManager emdkManager) {
this.emdkManager = emdkManager;
Log.d(TAG, "EMDK opened");
try{
serialCommMan = (SerialCommManager) this.emdkManager.getInstance(EMDKManager.FEATURE_TYPE.SERIALCOMM_EX);
List<SerialPortInfo> serialPorts = serialCommMan.getSupportedPorts();
serialComm = serialCommMan.getPort(serialPorts.get(0));
System.out.println("Supported Ports::::::" + serialPorts);
Thread readThread = new Thread(new Runnable() {
#Override
public void run() {
String statusText;
if (serialComm != null) {
try{
serialComm.enable();
statusText = "Serial comm channel enabled";
setEnabled(true);
} catch(SerialCommException e){
Log.d(TAG, e.getMessage());
e.printStackTrace();
statusText = e.getMessage();
setEnabled(false);
}
} else {
statusText = FEATURE_TYPE.SERIALCOMM_EX.toString() + " Feature not supported or initilization error.";
setEnabled(false);
}
displayMessage(statusText);
}
});
readThread.start();
}
catch(Exception e)
{
Log.d(TAG, e.getMessage());
e.printStackTrace();
displayMessage(e.getMessage());
}
}
#Override
public void onClosed() {
if(emdkManager != null) {
emdkManager.release();
}
displayMessage("EMDK closed abruptly.");
}
private void addReadButtonEvents() {
readButton = (Button) findViewById(R.id.btnRead);
readButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread readThread = new Thread(new Runnable() {
#Override
public void run() {
setEnabled(false);
String statusText;
try {
byte[] readBuffer = serialComm.read(10000); //Timeout after 10 seconds
if(readBuffer != null) {
String tempString = new String(readBuffer);
statusText = "Data Read:\n" + tempString;
} else {
statusText = "No Data Available";
}
}catch (SerialCommException e) {
statusText ="read:"+ e.getResult().getDescription();
e.printStackTrace();
}
catch (Exception e) {
statusText = "read:"+ e.getMessage();
e.printStackTrace();
}
setEnabled(true);
displayMessage(statusText);
}
});
readThread.start();
}
});
}
#SuppressWarnings("SetTextI18n")
private void writeButtonEvents() {
writeButton = (Button) findViewById(R.id.btnWrite);
writeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setEnabled(false);
try {
String writeData = editText.getText().toString();
int bytesWritten = serialComm.write(writeData.getBytes(), writeData.getBytes().length);
statusView.setText("Bytes written: "+ bytesWritten);
} catch (SerialCommException e) {
statusView.setText("write: "+ e.getResult().getDescription());
}
catch (Exception e) {
statusView.setText("write: "+ e.getMessage() + "\n");
}
setEnabled(true);
}
});
}
#SuppressWarnings("SetTextI18n")
void displayMessage(String message) {
final String tempMessage = message;
runOnUiThread(new Runnable() {
public void run() {
statusView.setText(tempMessage + "\n");
}
});
}
void setEnabled(boolean enableState) {
final boolean tempState = enableState;
runOnUiThread(new Runnable() {
public void run() {
readButton.setEnabled(tempState);
writeButton.setEnabled(tempState);
editText.setEnabled(tempState);
}
});
}
}
Does the problem seem to be with my code or is there something I am not understanding about the device itself? Any help would be appreciated. Thank you for your time.

Related

Zebra RFD2000 TC20 RFID SDK

I am using the quick start example supplied in the Android developer guide (rfid-sdk-for-android-dg-en.pdf) and although it does work and scans RFID TAGS there seems to be a problem with the reliability of the scanning. I have tracked the problem down to the EventHandler Class, that the reader.Actions.getReadTags method sometimes returns null this is even if the RFID tags are next to the scanner.
Any help would be much appreciated
I have included the code that I am using:
package uk.co.assettrac.rfd2000_tc20_example;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.zebra.rfid.api3.*;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static Readers readers;
private static ArrayList<ReaderDevice> availableRFIDReaderList;
private static ReaderDevice readerDevice;
private static RFIDReader reader;
private static String TAG = "DEMO";
TextView textView;
private EventHandler eventHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// UI
textView = (TextView) findViewById(R.id.TagText);
// SDK
if (readers == null) {
readers = new Readers(this, ENUM_TRANSPORT.SERVICE_SERIAL);
}
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
try {
if (readers != null) {
if (readers.GetAvailableRFIDReaderList() != null) {
availableRFIDReaderList =
readers.GetAvailableRFIDReaderList();
if (availableRFIDReaderList.size() != 0) {
// get first reader from list
readerDevice = availableRFIDReaderList.get(0);
reader = readerDevice.getRFIDReader();
if (!reader.isConnected()) {
// Establish connection to the RFID Reader
reader.connect();
ConfigureReader();
return true;
}
}
}
}
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
Log.d(TAG, "OperationFailureException " + e.getVendorMessage());
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean) {
Toast.makeText(getApplicationContext(), "Reader Connected",
Toast.LENGTH_LONG).show();
//textView.setText("Reader connected");
}
}
}.execute();
}
private void ConfigureReader() {
if (reader.isConnected()) {
TriggerInfo triggerInfo = new TriggerInfo();
triggerInfo.StartTrigger.setTriggerType(START_TRIGGER_TYPE.START_TRIGGER_TYPE_IMMEDIATE);
triggerInfo.StopTrigger.setTriggerType(STOP_TRIGGER_TYPE.STOP_TRIGGER_TYPE_IMMEDIATE);
try {
// receive events from reader
if (eventHandler == null)
eventHandler = new EventHandler();
reader.Events.addEventsListener(eventHandler);
// HH event
reader.Events.setHandheldEvent(true);
// tag event with tag data
reader.Events.setTagReadEvent(true);
reader.Events.setAttachTagDataWithReadEvent(true);
// set trigger mode as rfid so scanner beam will not come
reader.Config.setTriggerMode(ENUM_TRIGGER_MODE.RFID_MODE, true);
// set start and stop triggers
reader.Config.setStartTrigger(triggerInfo.StartTrigger);
reader.Config.setStopTrigger(triggerInfo.StopTrigger);
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (reader != null) {
reader.Events.removeEventsListener(eventHandler);
reader.disconnect();
Toast.makeText(getApplicationContext(), "Disconnecting reader",
Toast.LENGTH_LONG).show();
reader = null;
readers.Dispose();
readers = null;
}
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read/Status Notify handler
// Implement the RfidEventsLister class to receive event notifications
public class EventHandler implements RfidEventsListener {
// Read Event Notification
public void eventReadNotify(RfidReadEvents e) {
// Recommended to use new method getReadTagsEx for better performance in case of large tag population
TagData[] myTags = reader.Actions.getReadTags(100);
if (myTags != null) {
for (int index = 0; index < myTags.length; index++) {
Log.d(TAG, "Tag ID " + myTags[index].getTagID());
if (myTags[index].getOpCode() ==
ACCESS_OPERATION_CODE.ACCESS_OPERATION_READ &&
myTags[index].getOpStatus() ==
ACCESS_OPERATION_STATUS.ACCESS_SUCCESS) {
if (myTags[index].getMemoryBankData().length() > 0) {
Log.d(TAG, " Mem Bank Data " + myTags[index].getMemoryBankData());
}
}
}
} else {
Log.d(TAG, "TagData Array Null");
}
}
// Status Event Notification
public void eventStatusNotify(RfidStatusEvents rfidStatusEvents) {
Log.d(TAG, "Status Notification: " +
rfidStatusEvents.StatusEventData.getStatusEventType());
if (rfidStatusEvents.StatusEventData.getStatusEventType() ==
STATUS_EVENT_TYPE.HANDHELD_TRIGGER_EVENT) {
if
(rfidStatusEvents.StatusEventData.HandheldTriggerEventData.getHandheldEvent() ==
HANDHELD_TRIGGER_EVENT_TYPE.HANDHELD_TRIGGER_PRESSED) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
reader.Actions.Inventory.perform();
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
if (rfidStatusEvents.StatusEventData.HandheldTriggerEventData.getHandheldEvent() ==
HANDHELD_TRIGGER_EVENT_TYPE.HANDHELD_TRIGGER_RELEASED) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
reader.Actions.Inventory.stop();
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
}
}
}
}
After reading the docs for a long time I found that the line
reader.Events.setAttachTagDataWithReadEvent(true);
was causing the problem.

onScannerClosedWithResult(no.nordicsemi.android.beacon.Beacon)' on a null object reference

I am trying to write a app which scans for beacons,
when I login to the app, it starts scanning but after some seconds it just crashes. if I turn off my bluetooth it works fine. this is the error I get:
Process: com.noxel.apppaneladmintry2, PID: 11192
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.niloofar.showroom.BeaconsFragment.onScannerClosed()' on a null object reference
at com.example.niloofar.showroom.BeaconScannerFragment.onCancel(BeaconScannerFragment.java:56)
at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java:1260)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:921)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:716)
and this is my code,
package com.example.niloofar.showroom;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.UUID;
import no.nordicsemi.android.beacon.Beacon;
import no.nordicsemi.android.beacon.BeaconRegion;
import no.nordicsemi.android.beacon.BeaconServiceConnection;
import no.nordicsemi.android.beacon.Proximity;
import no.nordicsemi.android.beacon.ServiceProxy;
public class drawermenu extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, BeaconServiceConnection.BeaconsListener, BeaconServiceConnection.RegionListener {
public ProfileFragment profileFragment;
private static final String SCANNER_FRAGMENT = "scannerFragment";
public static final String NRF_BEACON_SERVICE_URL = "market://details?id=no.nordicsemi.android.beacon.service";
public static final String OPENED_FROM_LAUNCHER = "no.nordicsemi.android.nrfbeacon.extra.opened_from_launcher";
public static final String EXTRA_OPEN_DFU = "no.nordicsemi.android.nrfbeacon.extra.open_dfu";
public static final int BEACON_COMPANY_ID = 0x0059;
private static final int REQUEST_ENABLE_BT = 1;
private boolean mServiceConnected;
private boolean mFragmentResumed;
private DatabaseHelper mDatabaseHelper;
private BeaconAdapter mAdapter;
private BeaconScannerFragment mScannerFragment;
int minor;
public Fragment fragment=null;
public FragmentA fragmentA;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(this, "Device dows not support Bluetooth", Toast.LENGTH_LONG);
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
mDatabaseHelper = new DatabaseHelper(this);
getSupportActionBar().setElevation(0);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}catch (Exception ex) {
Log.d("ERROR", ex.getMessage());
}
}
#Override
public void onStart() {
super.onStart();
// final Cursor cursor = mDatabaseHelper.getAllRegions();
bindService();
}
#Override
public void onResume() {
super.onResume();
// startScanning();
if (mFragmentResumed)
return;
mFragmentResumed = true;
// bindService();
onAddOrEditRegion();
}
#Override
public void onPause() {
super.onPause();
// stopScanning();
if (!mFragmentResumed)
return;
mFragmentResumed = false;
unbindService();
}
private BeaconServiceConnection mServiceConnection = new BeaconServiceConnection() {
#Override
public void onServiceConnected() {
try {
mServiceConnected = true;
final BeaconScannerFragment scannerFragment = mScannerFragment;
if (scannerFragment != null) {
startRangingBeaconsInRegion(BEACON_COMPANY_ID, BeaconRegion.ANY_UUID, scannerFragment);
} else {
// final FragmentManager fm = getChildFragmentManager();
// if (fm.getBackStackEntryCount() == 0) {
// Start scan only if there is no any other fragment (Mona Lisa) open
startScanning();
// }
}
} catch (Exception ex) {
Log.d("ERROR", ex.getMessage());
}
}
#Override
public void onServiceDisconnected() {
try {
mServiceConnected = false;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
};
public void onAddOrEditRegion() {
// if (!ensurePermission())
// return;
try {
stopScanning();
// mScannerFragment=null;
final BeaconScannerFragment fragment = mScannerFragment = new BeaconScannerFragment();
fragment.show(getSupportFragmentManager(), SCANNER_FRAGMENT);
// fragment.isHidden();
mServiceConnection.startRangingBeaconsInRegion(BEACON_COMPANY_ID, BeaconRegion.ANY_UUID, fragment);
}
catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void startScanning() {
try {
if (mServiceConnected) {
startScanning(mServiceConnection);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void stopScanning() {
try {
if (mServiceConnected) {
stopScanning(mServiceConnection);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void bindService() {
// if (!ensurePermission())
// return;
try {
final boolean success = ServiceProxy.bindService(this, mServiceConnection);
if (!success) {
new AlertDialog.Builder(this).setTitle(R.string.service_required_title).setMessage(R.string.service_required_message)
.setPositiveButton(R.string.service_required_store, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int which) {
final Intent playIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(MainActivity.NRF_BEACON_SERVICE_URL));
startActivity(playIntent);
}
}).setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(final DialogInterface dialog) {
dialog.dismiss();
finish();
}
}).show();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void unbindService() {
try {
if (mServiceConnected) {
// Unbinding service will stop all active scanning listeners
ServiceProxy.unbindService(this, mServiceConnection);
mDatabaseHelper.resetSignalStrength();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void startScanning(final BeaconServiceConnection serviceConnection) {
try {
final Cursor cursor = mDatabaseHelper.getAllRegions();
while (cursor.moveToNext()) {
final UUID uuid = UUID.fromString(cursor.getString(2 /* UUID */));
final int major = cursor.getInt(3 /* MAJOR */);
final int minor = cursor.getInt(4 /* MINOR */);
final int event = cursor.getInt(6 /* EVENT */);
// We must start ranging for all beacons
serviceConnection.startRangingBeaconsInRegion(BEACON_COMPANY_ID, uuid, major, minor, this);
// And additionally start monitoring only for those with these two events set
if (event == BeaconContract.EVENT_IN_RANGE || event == BeaconContract.EVENT_OUT_OF_RANGE)
serviceConnection.startMonitoringForRegion(BEACON_COMPANY_ID, uuid, major, minor, this);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void stopScanning(final BeaconServiceConnection serviceConnection) {
try {
if (serviceConnection != null) {
serviceConnection.stopMonitoringForRegion(this);
serviceConnection.stopRangingBeaconsInRegion(this);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
#Override
public void onBeaconsInRegion(final Beacon[] beacons, final BeaconRegion region) {
try {
if (beacons.length > 0) {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
// Check and fire events
final int event = cursor.getInt(6 /* EVENT */);
for (final Beacon beacon : beacons) {
if (event == BeaconContract.EVENT_ON_TOUCH && Proximity.IMMEDIATE.equals(beacon.getProximity()) && Proximity.NEAR.equals(beacon.getPreviousProximity())) {
fireEvent(cursor);
break;
}
if (event == BeaconContract.EVENT_GET_NEAR && Proximity.NEAR.equals(beacon.getProximity()) && Proximity.FAR.equals(beacon.getPreviousProximity())) {
fireEvent(cursor);
break;
}
}
// Update signal strength in the database
float accuracy = 5;
for (final Beacon beacon : beacons)
if (Proximity.UNKNOWN != beacon.getProximity() && beacon.getAccuracy() < accuracy)
accuracy = beacon.getAccuracy();
accuracy = -20 * accuracy + 100;
mDatabaseHelper.updateRegionSignalStrength(cursor.getLong(0 /* _ID */), (int) accuracy);
}
} finally {
cursor.close();
}
mAdapter.swapCursor(mDatabaseHelper.getAllRegions());
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
#Override
public void onEnterRegion(final BeaconRegion region) {
try {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
final int event = cursor.getInt(6 /* EVENT */);
if (event == BeaconContract.EVENT_IN_RANGE) {
fireEvent(cursor);
}
}
} finally {
cursor.close();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
#Override
public void onExitRegion(final BeaconRegion region) {
try {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
final int event = cursor.getInt(6 /* EVENT */);
if (event == BeaconContract.EVENT_OUT_OF_RANGE) {
fireEvent(cursor);
}
}
} finally {
cursor.close();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void fireEvent(final Cursor cursor) {
try {
final boolean enabled = cursor.getInt(9 /* ENABLED */) == 1;
if (!enabled)
return;
final int action = cursor.getInt(7 /* ACTION */);
final String actionParam = cursor.getString(8 /* ACTION PARAM */);
switch (action) {
case BeaconContract.ACTION_MONA_LISA: {
stopScanning();
// final DialogFragment dialog = new MonalisaFragment();
// dialog.show(mParentFragment.getChildFragmentManager(), "JIRNG");
break;
}
case BeaconContract.ACTION_SILENT: {
stopScanning();
// final DialogFragment dialog = new tarh();
// dialog.show(mParentFragment.getChildFragmentManager(), "JIRING");
break;
}
case BeaconContract.ACTION_ALARM: {
stopScanning();
// final DialogFragment dialog = new rest();
// dialog.show(mParentFragment.getChildFragmentManager(), "Jiring");
break;
}
case BeaconContract.ACTION_URL: {
stopScanning();
try {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(actionParam));
startActivity(intent);
} catch (final ActivityNotFoundException e) {
Toast.makeText(this, R.string.no_application, Toast.LENGTH_SHORT).show();
}
break;
}
case BeaconContract.ACTION_APP: {
stopScanning();
try {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setPackage(actionParam);
startActivity(intent);
} catch (final ActivityNotFoundException e) {
Toast.makeText(this, R.string.no_given_application, Toast.LENGTH_SHORT).show();
}
break;
}
case BeaconContract.ACTION_TASKER:
// switch (TaskerIntent.testStatus(getActivity())) {
// case OK:
// final TaskerIntent i = new TaskerIntent(actionParam);
final BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent recIntent) {
// if (recIntent.getBooleanExtra(TaskerIntent.EXTRA_SUCCESS_FLAG, false))
Toast.makeText(drawermenu.this, R.string.tasker_success, Toast.LENGTH_SHORT).show();
drawermenu.this.unregisterReceiver(this);
}
};
// getActivity().registerReceiver(br, i.getCompletionFilter());
// Start the task
// getActivity().sendBroadcast(i);
break;
// case NotEnabled:
// Toast.makeText(getActivity(), R.string.tasker_disabled, Toast.LENGTH_SHORT).show();
// break;
// case AccessBlocked:
// Toast.makeText(getActivity(), R.string.tasker_external_access_denided, Toast.LENGTH_SHORT).show();
// break;
// case NotInstalled:
// Toast.makeText(getActivity(), R.string.tasker_not_installed, Toast.LENGTH_SHORT).show();
// break;
default:
Toast.makeText(this, R.string.tasker_error, Toast.LENGTH_SHORT).show();
break;
}
// break;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void onEditRegion(final long id) {
// final Intent intent = new Intent(this, BeaconsDetailsActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
// intent.putExtra(BeaconsDetailsActivity.ID, id);
// startActivity(intent);
}
public void onScannerClosedWithResult(final Beacon beacon) {
try {
mServiceConnection.stopRangingBeaconsInRegion(mScannerFragment);
mScannerFragment.dismiss();
mScannerFragment = null;
// final Cursor cursor = mDatabaseHelper.findRegionByBeacon(beacon);
minor = beacon.getMinor();
Intent intenta = new Intent(drawermenu.this, FragmentA.class);
switch (minor) {
case 99:
// startActivity(intenta);
popUp();
break;
case 246:
// startActivity(intenta);
// Toast.makeText(MainActivity.this, "246", Toast.LENGTH_LONG).show();
popUp();
break;
case 63:
popUp();
break;
case 104:
popUp();
break;
}
}
catch (Exception ex)
{
Log.e("ERROR", ex.getMessage());
}
}
private void popUp()
{
new Handler().post(new Runnable() {
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(drawermenu.this,FragmentA.class);
// mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
drawermenu.this.startActivity(mainIntent);
// Splash.this.finish();
}
});
}
public void onScannerClosed() {
try {
mServiceConnection.stopRangingBeaconsInRegion(mScannerFragment);
mScannerFragment = null;
startScanning();
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public DatabaseHelper getDatabaseHelper() {
return mDatabaseHelper;
}
private boolean ensureBleExists() {
try {
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show();
return false;
}
return true;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
return false;
}
}
private boolean isBleEnabled() {
try {
final BluetoothManager bm = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
final BluetoothAdapter ba = bm.getAdapter();
return ba != null && ba.isEnabled();
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
return false;
}
}
private void enableBle() {
try {
final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_home) {
// Handle the camera action
fragment = new ProfileFragment();
} else if (id == R.id.nav_points) {
fragment = new PointFragment();
} else if (id == R.id.nav_coupons) {
fragment = new CouponFragment();
} else if (id == R.id.nav_about) {
fragment = new AboutFragment();
}
fragmentTransaction.replace(R.id.appbar, fragment,fragment.getClass().getSimpleName());
fragmentTransaction.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and this is the code which error is referring to:
package com.example.niloofar.showroom;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import no.nordicsemi.android.beacon.Beacon;
import no.nordicsemi.android.beacon.BeaconRegion;
import no.nordicsemi.android.beacon.BeaconServiceConnection;
import no.nordicsemi.android.beacon.Proximity;
/**
* Created by niloofar on 11/9/2016.
*/
public class BeaconScannerFragment extends DialogFragment implements BeaconServiceConnection.BeaconsListener {
// public class BeaconScannerFragment extends DialogFragment implements BeaconServiceConnection.BeaconsListener {
private boolean mCompleted;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCompleted = false;
}
#Override
public void onBeaconsInRegion(final Beacon[] beacons, final BeaconRegion region) {
if (!mCompleted) {
for (final Beacon beacon : beacons)
if (Proximity.IMMEDIATE == beacon.getProximity()) {
mCompleted = true;
final BeaconsFragment parentFragment = (BeaconsFragment) getParentFragment();
parentFragment.onScannerClosedWithResult(beacon);
dismiss();
break;
}
}
}
#NonNull
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
return new AlertDialog.Builder(getContext())
.setView(R.layout.fragment_scan).create();
}
#Override
public void onCancel(final DialogInterface dialog) {
super.onCancel(dialog);
final BeaconsFragment targetFragment = (BeaconsFragment) getParentFragment();
targetFragment.onScannerClosed();
}}
does anyone know how my problem will be solved?
This is the place where your problem occurs:
final BeaconsFragment parentFragment = (BeaconsFragment) getParentFragment();
parentFragment.onScannerClosedWithResult(beacon);
You initialize parentFragment, but the NullPointerException is thrown when you try to call onScannerClosedWithResult. This means that parentFragment is null. To solve this, you have three options. The first option is to use try-catch where you handle the NullPointerException. The second option is to make sure that getParentFragment will never return null. The third option is to fail gracefully when null is returned:
final BeaconsFragment parentFragment = (BeaconsFragment) getParentFragment();
if (parentFragment == null) {
parentFragment.onScannerClosedWithResult(beacon);
}

Recieving sensor output continiously

I am trying to control an arduino micro controller from android phone.
I need help to to continuously receive the output from the temperature sensor and display it on text view.
Here is the code:
package com.war10ck6001gmail.finalproject;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends ActionBarActivity {
public ToggleButton fan, light, manauto;
public Button inc, dec;
public TextView temp;
public Toolbar mToolbar;
TCPClient mTcpClient = null;
public connectTask conctTask = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// connect to the server
temp = (TextView) findViewById(R.id.temprature);
fan = (ToggleButton) findViewById(R.id.fanbutton);
light = (ToggleButton) findViewById(R.id.lightbutton);
manauto = (ToggleButton) findViewById(R.id.manauto);
inc = (Button) findViewById(R.id.increment);
dec = (Button) findViewById(R.id.decrement);
Automatic(light);
Automatic(fan);
Automatic(inc);
Automatic(dec);
conctTask = new connectTask();
conctTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
mTcpClient = null;
manauto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Manual(light);
Manual(fan);
Manual(inc);
Manual(dec);
mTcpClient.sendMessage("Man");
}
else {
Automatic(light);
Automatic(fan);
Automatic(inc);
Automatic(dec);
mTcpClient.sendMessage("Auto");
}
}
});
light.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mTcpClient.sendMessage("0");
}
else {
mTcpClient.sendMessage("1");
}
}
});
fan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mTcpClient.sendMessage("2");
}
else {
mTcpClient.sendMessage("3");
}
}
});
inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTcpClient.sendMessage("4");
}
});
dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTcpClient.sendMessage("5");
}
});
}
public void Automatic(Button btn) {
btn.setEnabled(false);
btn.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
}
public void Manual(Button btn) {
btn.setEnabled(true);
btn.getBackground().setColorFilter(null);
}
public class connectTask extends AsyncTask<String, String, TCPClient> {
String finalmessage;
#Override
protected TCPClient doInBackground(final String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(final String message) {
try {
//this method calls the onProgressUpdate
//publishProgress(message);
if (message != null) {
//finalmessage = message;
runOnUiThread(new Runnable() {
#Override
public void run() {
temp.setText(message);
}
});
System.out.println("Return Message from Socket::::: >>>>> " + message);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
mTcpClient.run();
if (mTcpClient != null) {
mTcpClient.sendMessage("Initial Message when connected with Socket Server");
}
/* runOnUiThread(new Runnable() {
#Override
public void run() {
temp.setText(finalmessage);
}
});*/
return null;
}
}
#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;
}
#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) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
return true;
}
if (id == R.id.action_master) {
return true;
}
if (id == R.id.action_bedroom) {
Intent intent = new Intent(getApplicationContext(), Bedroom.class);
startActivity(intent);
return true;
}
if (id == R.id.action_Cbedroom) {
Intent intent = new Intent(getApplicationContext(), Cbedroom.class);
startActivity(intent);
return true;
}
if (id == R.id.action_diningroom) {
Intent intent = new Intent(getApplicationContext(), Diningroom.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
here is the class which has the onmessage recieved
public class TCPClient {
public String serverMessage;
/**
* Specify the Server Ip Address here. Whereas our Socket Server is started.
*/
public static final String SERVERIP = "10.5.38.148"; // your computer IP address
public static final int SERVERPORT = 8888;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
private PrintWriter out = null;
private BufferedReader in = null;
MainActivity mainActivity = null;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TCPClient(final OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message text entered by client
*/
public void sendMessage(String message) {
if (out != null && !out.checkError()) {
System.out.println("message: " + message);
out.println(message);
out.flush();
}
}
public void stopClient() {
mRun = false;
}
public void run() {
mRun = true;
while (mRun) {
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP SI Client", "SI: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP SI Client", "SI: Sent.");
Log.e("TCP SI Client", "SI: Done.");
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
}
serverMessage = null;
}
catch (Exception e) {
Log.e("TCP SI Error", "SI: Error", e);
e.printStackTrace();
}
finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
}
catch (Exception e) {
Log.e("TCP SI Error", "SI: Error", e);
}
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}

solve android chat application

I designed a chat application but if I write text and click on send the application is force closed. I send username, ip and port information to the other activity.
messaging code :
import java.io.UnsupportedEncodingException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.chat.IAppManager;
import com.android.chat.IMService;
import com.android.chat.FriendController;
import com.android.chat.LocalStorageHandler;
import com.android.chat.FriendInfo;
import com.android.chat.MessageInfo;
import com.android.chats.R;
public class Messaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
private EditText messageText;
private EditText messageHistoryText;
private Button sendMessageButton;
private IAppManager imService;
private FriendInfo friend = new FriendInfo();
private LocalStorageHandler localstoragehandler;
private Cursor dbCursor;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Messaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging_screen); //messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
friend.userName = extras.getString(FriendInfo.USERNAME);
friend.ip = extras.getString(FriendInfo.IP);
friend.port = extras.getString(FriendInfo.PORT);
String msg = extras.getString(MessageInfo.MESSAGETEXT);
setTitle("Messaging with " + friend.userName);
// EditText friendUserName = (EditText) findViewById(R.id.friendUserName);
// friendUserName.setText(friend.userName);
localstoragehandler = new LocalStorageHandler(this);
dbCursor = localstoragehandler.get(friend.userName, IMService.USERNAME );
if (dbCursor.getCount() > 0){
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())&&noOfScorer<dbCursor.getCount())
{
noOfScorer++;
this.appendToMessageHistory(dbCursor.getString(2) , dbCursor.getString(3));
dbCursor.moveToNext();
}
}
localstoragehandler.close();
if (msg != null)
{
this.appendToMessageHistory(friend.userName , msg);
((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel((friend.userName+msg).hashCode());
}
sendMessageButton.setOnClickListener(new OnClickListener(){
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = messageText.getText();
if (message.length()>0)
{
appendToMessageHistory(imService.getUsername(), message.toString());
localstoragehandler.insert(imService.getUsername(), friend.userName, message.toString());
messageText.setText("");
Thread thread = new Thread(){
public void run() {
try {
if (imService.sendMessage(imService.getUsername(), friend.userName, message.toString()) == null)
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
//showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}});
messageText.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == 66){
sendMessageButton.performClick();
return true;
}
return false;
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id)
{
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1)
{
return null;
}
else
{
return new AlertDialog.Builder(Messaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(messageReceiver);
unbindService(mConnection);
FriendController.setActiveFriend(null);
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(Messaging.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.TAKE_MESSAGE);
registerReceiver(messageReceiver, i);
FriendController.setActiveFriend(friend.userName);
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Bundle extra = intent.getExtras();
String username = extra.getString(MessageInfo.USERID);
String message = extra.getString(MessageInfo.MESSAGETEXT);
if (username != null && message != null)
{
if (friend.userName.equals(username)) {
appendToMessageHistory(username, message);
localstoragehandler.insert(username,imService.getUsername(), message);
}
else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(Messaging.this, username + " says '"+
message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
};
private MessageReceiver messageReceiver = new MessageReceiver();
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
messageHistoryText.append(username + ":\n");
messageHistoryText.append(message + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
logcat message:
if I write text and click on send the application is force closed. I send username, ip and port information to the other activity.
code messageing :
public class Messaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
private EditText messageText;
private EditText messageHistoryText;
private Button sendMessageButton;
private IAppManager imService;
private FriendInfo friend = new ir.android.chat.FriendInfo();
private LocalStorageHandler localstoragehandler;
private Cursor dbCursor;
public static String res="";
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Messaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging_screen); //messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
friend.userName = extras.getString(FriendInfo.USERNAME);
friend.userNamef = extras.getString(FriendInfo.USERNAMEF);
friend.ip = extras.getString(FriendInfo.IP);
friend.port = extras.getString(FriendInfo.PORT);
String msg = extras.getString(MessageInfo.MESSAGETEXT);
setTitle("Messaging with " + friend.userName);
// EditText friendUserName = (EditText) findViewById(R.id.friendUserName);
// friendUserName.setText(friend.userName);
localstoragehandler = new LocalStorageHandler(this);
dbCursor = localstoragehandler.get(friend.userName, IMService.USERNAME );
if (dbCursor.getCount() > 0){
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())&&noOfScorer<dbCursor.getCount())
{
noOfScorer++;
this.appendToMessageHistory(dbCursor.getString(2) , dbCursor.getString(3));
dbCursor.moveToNext();
}
}
localstoragehandler.close();
if (msg != null)
{
this.appendToMessageHistory(friend.userName , msg);
((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel((friend.userName+msg).hashCode());
}
sendMessageButton.setOnClickListener(new OnClickListener(){
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = messageText.getText();
if (message.length()>0)
{
//appendToMessageHistory(friend.userNamef, message.toString());
appendToMessageHistory(friend.userNamef, message.toString());
localstoragehandler.insert(friend.userNamef, friend.userName, message.toString());
messageText.setText("");
Thread thread = new Thread(){
public void run() {
try {
if (imService.sendMessage(friend.userNamef, friend.userName, message.toString()) == null)
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
//showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}});
messageText.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == 66){
sendMessageButton.performClick();
return true;
}
return false;
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id)
{
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1)
{
return null;
}
else
{
return new AlertDialog.Builder(Messaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(messageReceiver);
unbindService(mConnection);
FriendController.setActiveFriend(null);
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(Messaging.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.TAKE_MESSAGE);
registerReceiver(messageReceiver, i);
FriendController.setActiveFriend(friend.userName);
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Bundle extra = intent.getExtras();
String username = extra.getString(MessageInfo.USERID);
String message = extra.getString(MessageInfo.MESSAGETEXT);
if (username != null && message != null)
{
if (friend.userName.equals(username)) {
appendToMessageHistory(username, message);
localstoragehandler.insert(username,friend.userNamef, message);
}
else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(Messaging.this, username + " says '"+
message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
};
private MessageReceiver messageReceiver = new MessageReceiver();
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
messageHistoryText.append(username + ":\n");
messageHistoryText.append(message + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
log chat :
http://i.stack.imgur.com/USsul.png

DatagramSocket.receive only receives the first two Datagrams

I am sending some data to an android application over UDP. Therefore i created the following UDPReceiver-Class:
package com.example.urowatch;
import java.net.*;
import java.nio.ByteBuffer;
import java.io.*;
public class UDPReceiver extends Thread
{
private DatagramSocket m_Socket;
private int m_BufferSize;
private Boolean m_End = false;
private int m_TotalLength;
private int m_Received;
private byte[] m_Buffer;
private byte[] m_Result;
private Boolean m_IsNewResult = false;
private float m_Progress;
private int m_ImageCount = 0;
private int m_FrameErrors = 0;
public UDPReceiver(String name, int port, int bufferSize) throws IOException
{
super(name);
m_Socket = new DatagramSocket(port);
m_BufferSize = bufferSize;
m_Socket.setBroadcast(true);
m_Socket.setReceiveBufferSize(m_BufferSize);
}
public void run()
{
while(!m_End)
{
try
{
byte[] buf = new byte[m_BufferSize];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
m_Socket.receive(packet);
ProcessData(packet);
}
catch (IOException e)
{
if (!m_Socket.isClosed())
e.printStackTrace();
}
}
}
private void ProcessData(DatagramPacket packet)
{
if (packet.getLength() == 4)
{
ByteBuffer bb = ByteBuffer.wrap(packet.getData());
m_TotalLength = bb.getInt();
if (m_Received != 0)
m_FrameErrors++;
m_Received = 0;
m_Buffer = new byte[m_TotalLength];
}
else if (m_Buffer != null && m_Received != m_TotalLength)
{
int length = packet.getLength();
System.arraycopy(packet.getData(), 0, m_Buffer, m_Received, length);
m_Received += length;
m_Progress = 100 * (float)m_Received/(float)m_TotalLength;
if (m_Received == m_TotalLength)
{
m_Result = new byte[m_TotalLength];
System.arraycopy(m_Buffer, 0, m_Result, 0, m_TotalLength);
m_IsNewResult = true;
m_ImageCount++;
m_Received = 0;
}
}
}
public Boolean IsNewResult()
{
return m_IsNewResult;
}
public byte[] GetResult()
{
m_IsNewResult = false;
return m_Result;
}
public float GetProgress()
{
return m_Progress;
}
public float GetRatio()
{
return 100 * (float)m_ImageCount / (float)m_FrameErrors;
}
public void stopServer()
{
m_End = true;
if (m_Socket != null)
m_Socket.close();
}
}
And i am using this class like this:
package com.example.urowatch;
import java.io.IOException;
import java.text.DecimalFormat;
import android.os.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Build;
public class LiveActivity extends Activity {
private static ImageView m_ImageView1;
private static TextView m_TextView1;
private static DecimalFormat m_DF;
private static Context m_Context;
private UDPReceiver m_Receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
// Show the Up button in the action bar.
setupActionBar();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
m_ImageView1 = (ImageView)findViewById(R.id.imageView1);
m_TextView1 = (TextView)findViewById(R.id.textView1);
m_Context = this;
m_DF = new DecimalFormat("00.00");
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.live, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private static Handler MyHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == 100)
{
float[] infos = (float[])msg.obj;
m_TextView1.setText("Empfange Bild: " + m_DF.format(infos[0]) + "% (FrameErrors: " + m_DF.format(infos[1]) + "%)");
}
else if (msg.what == 101)
{
byte[] b = (byte[])msg.obj;
m_TextView1.setText("Empfange Bild: 100,00%");
m_ImageView1.setImageBitmap(BitmapFactory.decodeByteArray(b, 0, b.length));
}
else if (msg.what == 102)
{
AlertDialog.Builder b = new AlertDialog.Builder(m_Context);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + (Exception)msg.obj);
b.setNeutralButton("OK", null);
b.show();
}
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
if (m_Receiver != null)
m_Receiver.stopServer();
finish();
}
#Override
public void onPause()
{
m_Receiver.stopServer();
super.onPause();
}
#Override
protected void onResume()
{
try {
m_Receiver = new UDPReceiver("UDPReceiver", 5678, 1024);
m_Receiver.start();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + e1);
b.setNeutralButton("OK", null);
b.show();
}
// Thread thread = new Thread()
// {
// #Override
// public void run()
// {
// while(true)
// {
// try {
//sleep(250);
Toast.makeText(getBaseContext(), "Runing Thread", Toast.LENGTH_SHORT).show();
Update();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// MyHandler.sendMessage(MyHandler.obtainMessage(102, e));
// }
// }
// }
// };
// thread.start();
super.onResume();
}
public void buttonClick(View v)
{
Update();
}
private void Update()
{
if (m_Receiver != null)
{
if (m_Receiver.IsNewResult())
{
byte[] b = m_Receiver.GetResult();
MyHandler.sendMessage(MyHandler.obtainMessage(101, b));
}
else
{
float[] infos = new float[2];
infos[0] = m_Receiver.GetProgress();
infos[1] = m_Receiver.GetRatio();
MyHandler.sendMessage(MyHandler.obtainMessage(100, infos));
}
}
}
}
As you see i want to check the status of the UDPReceiver-Object (Is there a new complete byte[] ready?) by a thread. To update the GUI, the thread has to send a Message to MyHandler which will update the GUI.
In the moment i have to to click a button to raise the buttonClick-Event. Later on i want to do this in the commented thread-structure.
Now, here's my problem:
I start the Activity and everything works fine. Then i am starting to send ONE packet manually with my UDP-Sender (which works, i validated it with a C#-UDP-Receiver). The first packet get received fine. Then i send the second packet which get received, too. But from now on, my breakpoint at m_Socket.receive(packet); wont get hit anymore!
I have NO idea what this behaviour causes and it is very important for me to make this application work.
Please, if you have ANY Idea or just a guess, please let me know.

Categories

Resources