I got a few markers and update a position of this markers (I send request for server). But when I put new markers I did this:
public void putMarkers() {
Singleton si = Singleton.getInstance();
Drawable newMarker = getApplication().getResources().getDrawable(R.drawable.znacznik_new);
Drawable newMarkerAktywny = getApplication().getResources().getDrawable(R.drawable.ikona_znacznik_pojazd_aktywna);
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
activeOverlayItemArray.clear();
anotherOverlayItemArray.clear();
for(ObjectDefExtends object : si.getListaVisible()){
if (object.lon == null) object.lon = 0.0;
if (object.lat == null) object.lat = 0.0;
/*if (si.getListaVisible().get(a).lon!=null&&si.getListaVisible().get(a).lon!=0)*/
if (object == Singleton.getInstance().currentObject) {
activeOverlayItemArray.add(new OverlayItem(object.name,
object.name, new GeoPoint(object.lat, object.lon)));
} {
anotherOverlayItemArray.add(new OverlayItem(object.name,
object.name, new GeoPoint(object.lat, object.lon)));
}
}
anotherItemizedIconOverlay = new ItemizedIconOverlay<>(anotherOverlayItemArray, newMarker, new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
indexs = index + 1;
mPin.hideInfoWindow();
mapView.getOverlays().remove(mPin);
mPin.setPosition(anotherItemizedIconOverlay.getItem(index).getPoint());
mPin.setTitle(anotherItemizedIconOverlay.getItem(index).getTitle());
try {
tvStreetName.setText(getCityAndStreet(anotherItemizedIconOverlay.getItem(index).getPoint().getLatitude(), anotherItemizedIconOverlay.getItem(index).getPoint().getLongitude(), getBaseContext()));
} catch (IOException e) {
e.printStackTrace();
}
currentNumber = index;
Singleton.getInstance().setCurrentObjectIndex(currentNumber);
Log.e("azymut ", Singleton.getInstance().getListaODE().get(currentNumber).azimuth + "");
updateEverything();
mPin.showInfoWindow();
mapView.getOverlays().add(mPin);
return true;
}
#Override
public boolean onItemLongPress(final int index, final OverlayItem item) {
return false;
}
}, mResourceProxy);
activeItemizedIconOverlay = new ItemizedIconOverlay<>(activeOverlayItemArray, newMarkerAktywny, new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
mPin.hideInfoWindow();
mapView.getOverlays().remove(mPin);
mPin.setPosition(activeItemizedIconOverlay.getItem(index).getPoint());
mPin.setTitle(anotherItemizedIconOverlay.getItem(index).getTitle());
currentNumber = index;
Singleton.getInstance().setCurrentObjectIndex(currentNumber);
updateEverything();
mPin.showInfoWindow();
mapView.getOverlays().add(mPin);
return true;
}
#Override
public boolean onItemLongPress(final int index, final OverlayItem item) {
return false;
}
}, mResourceProxy);
for (int a = 0; a < anotherItemizedIconOverlay.size(); a++) {
if (si.listaVisible.indexOf(Singleton.getInstance().currentObject) == a) {
activeItemizedIconOverlay.removeAllItems();
activeItemizedIconOverlay.addItem(new OverlayItem(
si.getListaVisible().get(a).name,
si.getListaVisible().get(a).name,
new GeoPoint(si.getListaVisible().get(a).lat,
Singleton.getInstance().getListaVisible().get(a).lon)));
mPin.setPosition(anotherItemizedIconOverlay.getItem(a).getPoint());
mPin.setAnchor(0.5f, 0.5f);
mPin.setIcon(getResources().getDrawable(R.drawable.pusty));
mPin.setTitle(anotherItemizedIconOverlay.getItem(a).getTitle());
break;
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mapView.getOverlays().add(mPin);
mapView.getOverlays().add(anotherItemizedIconOverlay);
mapView.getOverlays().add(activeItemizedIconOverlay);
mapView.invalidate();
}
});
}
And this is how I update a position:
public void aktualizujCoInterwal(int interwal) {
aktualizacja = true;
executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new Runnable() {
public void run() {
Log.e("aktualizacja", "akt");
if (timeout) {
executor.shutdown();
timedOut();
} else {
aktualizacjaDanych();
}
}
}, 0, interwalAktualizacji, TimeUnit.SECONDS);
}
public void aktualizacjaDanych() {
SmokConnectorImplPortBinding srv1 = new SmokConnectorImplPortBinding(null, URL);
try {
Singleton si = Singleton.getInstance();
ObjectLastStateResult lastState2;
lastState2 = srv1.GetObjectLastState(uid, now);
int rozmiarNowych = lastState2.objectState.size();
int value = (Integer) lastState2.getProperty(0);
if (value != 1) {
timeout = true;
executor.shutdownNow();
timedOut();
} else {
int rozmiarObecnych = si.getListaODE().size();
runOnUiThread(new Runnable() {
#Override
public void run() {
//czyszczenie poprzednio dodanych na mape obiektow
anotherOverlayItemArray.clear();
activeOverlayItemArray.clear();
mapView.getOverlays().clear();
}
});
for (int i = 0; i < rozmiarNowych; i++) {
for (int b = 0; b < rozmiarObecnych; b++) {
if (si.getListaODE().get(b).id.equals(lastState2.objectState.get(i).id)) {
if (lastState2.objectState.get(i).lon != null && lastState2.objectState.get(i).lon.doubleValue() != 0) {
if (lastState2.objectState.get(i).lat != null && lastState2.objectState.get(i).lat.doubleValue() != 0) {
si.getListaODE().get(b).lat = lastState2.objectState.get(i).lat.doubleValue();
si.getListaODE().get(b).lon = lastState2.objectState.get(i).lon.doubleValue();
}
si.getListaODE().get(b).azimuth = lastState2.objectState.get(i).azimuth.intValue();
si.getListaODE().get(b).lastDataTime = lastState2.objectState.get(i).dateTime;
si.getListaODE().get(b).statusGPS = lastState2.objectState.get(i).statusGPS;
try {
si.getListaODE().get(b).mySensors = lastState2.objectState.get(i).sensors.sensor;
} catch (NullPointerException e) {
Log.e("Null", "sensory są puste");
}
si.getListaODE().get(b).description1 = lastState2.objectState.get(i).description1;
si.getListaODE().get(b).description2 = lastState2.objectState.get(i).description2;
si.getListaODE().get(b).velocity = lastState2.objectState.get(i).velocity.intValue();
try {
si.getListaODE().get(b).icons = lastState2.objectState.get(i).sensors.icon;
} catch (NullPointerException e) {
Log.e("Null", "sensory są puste");
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
now = DateTime.now();
Singleton si = Singleton.getInstance();
if (si.getListaVisible().size() > 0) {
obiektyNaMape();
updateEverything();
}
showCurrentMarker();
}
All my objects from servers have a azimuth and I rotate a markers icon from all markers, and when a update is done first of all I see a default markers and later I see a rotate markers.
Related
Рow to use if statements between two intent activities? I have two different activities collecting data from external sensors. I would like to control some GPIO pins of Activity1 based on the sensor values of Activity2.
Activity 1
public class RealTimeData extends AppCompatActivity {
private static final String TAG = "sensor_data";
private static final String FRAGMENT_DIALOG = "dialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_real_time_data);
Resources res = getResources();
GetAllResources();
OpenSerialPort();
}
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
private void GetAllResources() {
pressure1 = (TextView) findViewById(R.id.pressure);
temp1 = (TextView) findViewById(R.id.temperature);
co2ppm1 = (TextView) findViewById(R.id.co2);
humidity1 = (TextView) findViewById(R.id.humidity);
pressure1data = (TextView) findViewById(R.id.pressureData);
temp1data = (TextView) findViewById(R.id.temperatureData);
co2ppm1data = (TextView) findViewById(R.id.co2Data);
humidity1data = (TextView) findViewById(R.id.humidityData);
}
private sensorDataApplication sensordata = new sensorDataApplication();
private UartApplication[] mSerialport = {null, null};
private void SetValues()
{
TextView tv =(TextView) findViewById(R.id.pressureData);
tv.setText(String.valueOf(sensordata.get_pressure_value(0)));
tv =(TextView) findViewById(R.id.temperatureData);
tv.setText(String.valueOf(sensordata.get_temperature_value(0)));
tv =(TextView) findViewById(R.id.co2Data);
tv.setText(String.valueOf(sensordata.get_co2_value(0)));
tv =(TextView) findViewById(R.id.humidityData);
tv.setText(String.valueOf(sensordata.get_humidity_value(0)));
}
private void OpenSerialPort() {
new sensorDataApplication();
try {
int i =0;
for(String devicePath : Configs.uartdevicePath) {
mSerialport[i] = new UartApplication(new File(devicePath), mReaderCallback);
i++;
}
} catch (SecurityException e) {
ErrorMessage.newInstance(getString(R.string.error_serial))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (IOException e) {
ErrorMessage.newInstance(getString(R.string.error_unknown))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (InvalidParameterException e) {
ErrorMessage.newInstance(getString(R.string.error_uart_config))
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
}
private final UartApplication.ReaderCallback mReaderCallback=
new UartApplication.ReaderCallback() {
#Override
public void onDataReceived(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
public void run() {
if (pressure1 != null) {
String received_str = new String(buffer, 0, size);
//uartRx.append(received_str);
sensordata.parse_and_update_sensordata(received_str);
SetValues();
Log.e(TAG,"received packet "+received_str);
}
}
});
}
};
TextWatcher mUartTxCallback = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(max(start,before) < s.length()) {
String changedStr = s.toString().substring(max(start, before), s.length());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable var1) {
}
};
private void CloseSerialPort(int idx)
{
mSerialport[idx].closeSerialPort();
}
private void WriteSerialPort(String writeString, int idx)
{
mSerialport[idx].writeData(writeString);
}
private static byte[] hexStringToByteArray(String s) {
int len = s.length();
s.toUpperCase();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
private static String toHexString(byte[] ba) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < ba.length; i++)
str.append(String.format("%02x", ba[i]));
return str.toString().toUpperCase();
}
private TextView pressure1;
private TextView temp1;
private TextView co2ppm1;
private TextView humidity1;
private TextView pressure1data;
private TextView temp1data;
private TextView co2ppm1data;
private TextView humidity1data;
}
Activity 2
public class ManualControl extends AppCompatActivity {
static {
System.loadLibrary("native-lib");
}
List<gpioApplication> mGPIO = new ArrayList<>();
private static final String FRAGMENT_DIALOG = "dialog";
private int[] mGPIOList = null;
private CheckBox[] cbGPIO;
private final gpioApplication.InterruptCallback mGPIOCallback =
new gpioApplication.InterruptCallback() {
#Override
public void onDataReceived(final int GPIOnum, final int value) {
runOnUiThread(new Runnable() {
public void run() {
//Do Nothing
CheckBox cbnGPIO = GetCheckBoxGpio(GPIOnum);
cbnGPIO.setOnCheckedChangeListener(null);
if (cbnGPIO != null)
cbnGPIO.setChecked(value > 0 ? true : false);
cbnGPIO.setOnCheckedChangeListener(mGPIOCheckBoxCallback);
}
});
}
};
private final CompoundButton.OnCheckedChangeListener mGPIOCheckBoxCallback =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
int gpioID = Integer.parseInt(buttonView.getHint().toString());
int GPIOValue = buttonView.isChecked() == true ? 1 : 0;
if (gpioID < mGPIOList.length) {
gpioApplication gpio = mGPIO.get(gpioID);
gpio.GPIOWrite(GPIOValue);
}
}
};
private CheckBox GetCheckBoxGpio(int GPIOnum) {
if (GPIOnum < mGPIOList.length)
return cbGPIO[GPIOnum];
return null;
}
private void GetAllResources() {
cbGPIO = new CheckBox[20];
cbGPIO[9] = (CheckBox) findViewById(R.id.checkBox_GPIO92);
cbGPIO[0] = (CheckBox) findViewById(R.id.checkBox_GPIO16);
cbGPIO[1] = (CheckBox) findViewById(R.id.checkBox_GPIO17);
cbGPIO[6] = (CheckBox) findViewById(R.id.checkBox_GPIO69);
cbGPIO[2] = (CheckBox) findViewById(R.id.checkBox_GPIO23);
for (int i = 0; i < mGPIOList.length; i++) {
if (i == 9 || i == 0 || i == 1 || i == 6 || i == 2) {
GetCheckBoxGpio(i).setText(Integer.toString(mGPIOList[i]));
GetCheckBoxGpio(i).setEnabled(true);
}
}
}
private final CompoundButton.OnCheckedChangeListener mIntCheckBoxCallback =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
int gpioID = Integer.parseInt(buttonView.getHint().toString());
boolean IntValue = buttonView.isChecked();
if (gpioID < mGPIOList.length) {
/*Use IntValue Re-configure GPIO Interrupt Here*/
mGPIO.get(gpioID).ConfigureInterrupt(IntValue);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_control);
try {
mGPIOList = gpio_list;
GetAllResources();
for (int i = 0; i < mGPIOList.length; i++) {
GPIOOpen(i);
}
ConfigureCallbacks();
GetAllResources();
} catch (Exception e) {
ErrorMessage.newInstance(e.getLocalizedMessage())
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
}
private void ConfigureCallbacks() {
ConfigureGPIOCheckboxCallback();
}
private void ConfigureGPIOCheckboxCallback() {
for (int i = 0; i < mGPIOList.length; i++) {
if (i == 9 || i == 0 || i == 1 || i == 6 || i == 2) {
cbGPIO[i].setOnCheckedChangeListener(mGPIOCheckBoxCallback);
}
}
}
private void GPIOOpen(int GPIOnum) {
if (GPIOnum == 9 || GPIOnum == 0 || GPIOnum == 1 || GPIOnum == 6 || GPIOnum == 2) {
mGPIO.add(new gpioApplication());
try {
mGPIO.get(GPIOnum).GPIOOpen(GPIOnum, mGPIOList[GPIOnum], mGPIOCallback);
} catch (SecurityException e) {
ErrorMessage.newInstance(getString(R.string.error_gpio))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (IOException e) {
ErrorMessage.newInstance(getString(R.string.error_unknown))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (InvalidParameterException e) {
ErrorMessage.newInstance(getString(R.string.error_gpio_config))
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
} else {
mGPIO.add(null);
}
}
}
In the above codes the GPIO pins must be controlled by the co2ppm1 sensor values (If the co2ppm1 sensor value is above 2000, it must turn ON GPIO 9 pin).
I get out of memory error if the function doesWifiExist is false if it is true every thing works normally.Can someone tell me what m i doing wrong
The idea is to get a list of wifi networks nearby and check if the inserted network exists in the list.
Here is the wifi network scanning code and the the function that checks if the wifi network exists.
MainActivity:
private WiFiConnection _wifiConnection = null;
static final int MY_PERMISSIONS_REQUEST = 1042;
private static final String PERMISSIONS_TAG = "PERMISSION";
...
#Override
protected void onStart() {
super.onStart();
_wifiConnection = new WiFiConnection(this);
startScan();
}
#Override
protected void onStop() {
super.onStop();
_wifiConnection.stopScan();
unregisterReceiver(_wifiScanReceiver);
}
void startScan() {
checkPermission(this);
registerReceiver(_wifiScanReceiver,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Thread t = new Thread(_wifiConnection.getWifiScanner());
t.start();
}
private final BroadcastReceiver _wifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
if (_wifiConnection != null && _wifiConnection.isWifiEnabled()) {
_wifiConnection.updateScanData();
}
}
}
};
public static boolean checkPermission(Activity activity) {
boolean permission = true;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<String> requiringList = new ArrayList<>();
permission = activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
Log.d(PERMISSIONS_TAG, "ACCESS_COARSE_LOCATION: " + permission);
if (!permission) {
requiringList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (requiringList.size() > 0) {
String[] stringArray = requiringList.toArray(new String[0]);
activity.requestPermissions(stringArray, MY_PERMISSIONS_REQUEST);
}
}
return permission;
}
private boolean doesWifiExist(String s){
String[] array = s.split(" ");
String ssid = array[0];
boolean flag = false;
//Check if wifi exists in the area
for(int i = 0 ; i < _wifiConnection.getListSSIDs().size(); i++){
if(_wifiConnection.getListSSIDs().get(i).equals(ssid)){
flag = true;
break;
}
}
return flag;
}
WiFiConnection class:
public class WiFiConnection
{
private static final int SCAN_INTERVAL = 5000;
final private List<String> _listSSIDs = new ArrayList<>();
private WifiManager _wifiManager;
private final WiFiScanner _startScan = new WiFiScanner();
private List<ScanResult> scanResults;
WiFiConnection(Activity activity) {
_wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}
//Puts wifi networks in a list
public List<String> getListSSIDs() {
for(int i = 0; i < scanResults.size(); i++)
{
_listSSIDs.add(scanResults.get(i).SSID);
}
return _listSSIDs;
}
WiFiScanner getWifiScanner() { return _startScan; }
void stopScan() { _startScan.stop(); }
boolean isWifiEnabled() { return _wifiManager.isWifiEnabled(); }
//Gets the wifi networks
void updateScanData() {
if ((_wifiManager != null && _wifiManager.isWifiEnabled())) {
scanResults = _wifiManager.getScanResults();
}
}
//Scans at an interval
private class WiFiScanner implements Runnable
{
private boolean _stop = false;
public void stop() {_stop = true;}
#Override
public void run() {
while (!_stop) {
_listSSIDs.clear();
_wifiManager.startScan();
try {
Thread.sleep(SCAN_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
The code where doesWifiExist is used.
//Check if wifi exists in the area
if(doesWifiExist(barcode.displayValue)){
//Connects to wifi
WifiConnect(barcode.displayValue);
//Saves item in db
insertItem();
if(networkSecurity.equals("None")){
networkPass = empty;
}
//Adds item to recyclerview
historyItems.add(0, new HistoryItem(wifiName + " " + networkSSID, wifiPass + " " + networkPass));
adapter.notifyItemInserted(0);
} else
Snackbar.make(findViewById(R.id.main_activity), R.string.snackInvalidQrCode, Snackbar.LENGTH_SHORT).show();
This method is called many times, and it everytime adds all scanResults at the end of field _listSSIDS.
public List<String> getListSSIDs() {
for(int i = 0; i < scanResults.size(); i++)
{
_listSSIDs.add(scanResults.get(i).SSID);
}
return _listSSIDs;
}
Use a local variable with a new List or better Set there.
Instead replace
for(int i = 0 ; i < _wifiConnection.getListSSIDs().size(); i++){
if(_wifiConnection.getListSSIDs().get(i).equals(ssid)){
flag = true;
break;
}
}
with
flag = _wifiConnection.hasSSID(String ssid);
public boolean hasSSID(String ssid) {
for (int i = 0; i < scanResults.size(); i++) {
if (ssid.equals(scanResults.get(i).SSID)) {
return true;
}
}
return false;
}
public class PerformanceDashboard extends MotherActivity {
String dashboardData;
int SELECTED_PAGE, SEARCH_TYPE, TRAY_TYPE;
List<String[]> cachedCounterUpdates = new ArrayList<String[]>();
List<DasDetails> docList = new ArrayList<DasDetails>();
ListView listViewDashboard;
DataAdapter dataAdap = new DataAdapter();
TextView noOfItems, userCount, totalLoginTime;
int itemsTotal = 0, userTotal = 0, totalTime = 0;
String KEYWORD = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (App.isTestVersion) {
Log.e("actName", "StoreOut");
}
if (bgVariableIsNull()) {
this.finish();
return;
}
setContentView(R.layout.dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setProgressBarIndeterminateVisibility(false);
lytBlocker = (LinearLayout) findViewById(R.id.lyt_blocker);
listViewDashboard = (ListView) findViewById(R.id.dashboard_listview);
noOfItems = ((TextView) findViewById(R.id.noOfItems));
userCount = ((TextView) findViewById(R.id.userCount));
totalLoginTime = ((TextView) findViewById(R.id.totalLoginTime));
new DataLoader().start();
listViewDashboard.setAdapter(dataAdap);
System.out.println("PerformanceDashboard. onCreate processOutData() -- item total " + itemsTotal); //0 i am not getting that adapter value i.e. 6
System.out.println("PerformanceDashboard. onCreate processOutData() -- user total " + userTotal); //0 i am not getting that adapter value i.e. 4
System.out.println("PerformanceDashboard. onCreate processOutData() -- total total " + totalTime); //0 i am not getting that adapter value i.e. 310
}
private class DataAdapter extends BaseAdapter {
#Override
public int getCount() {
return docList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.dashboard_item, null);
final DasDetails item = docList.get(position);
((TextView) convertView.findViewById(R.id.cMode))
.setText(item.cMode);
((TextView) convertView.findViewById(R.id.noOfItems))
.setText(item.totPickItemCount);
((TextView) convertView.findViewById(R.id.userCount))
.setText(item.userCount);
((TextView) convertView.findViewById(R.id.totalLoginTime))
.setText(item.totLoginTime);
TextView textView = ((TextView) convertView
.findViewById(R.id.avgSpeed));
Double s = Double.parseDouble(item.avgPickingSpeed);
textView.setText(String.format("%.2f", s));
if (position == 0 || position == 2 || position == 4) {
convertView.setBackgroundColor(getResources().getColor(
R.color.hot_pink));
} else if (position == 1 || position == 3 || position == 5) {
convertView.setBackgroundColor(getResources().getColor(
R.color.lightblue));
}
return convertView;
}
}
class ErrorItem {
String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public ErrorItem(HashMap<String, String> row) {
cMode = row.get(XT.MODE);
dDate = row.get(XT.DATE);
userCount = row.get(XT.USER_COUNT);
totLoginTime = row.get(XT.TOT_LOGIN_TIME);
totPickItemCount = row.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = row.get(XT.AVG_PICKING_SPEED);
}
}
private class DataLoader extends Thread {
#Override
public void run() {
super.run();
System.out.println("DataLoader dashboard");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair(C.PRM_IDX, C.GET_SUMMARY));
param.add(new BasicNameValuePair(C.PRM_HDR_DATA, "2016-07-04")); // yyyy-mm-dd
toggleProgressNoUINoBlock(true);
final String result = callService(C.WS_ST_PERFORMANCE_DASHBOARD,
param);
if (!App.validateXmlResult(actContext, null, result, true))
return;
runOnUiThread(new Runnable() {
#Override
public void run() {
Runnable r = new Runnable() {
#Override
public void run() {
dataAdap.notifyDataSetChanged();
toggleProgressNoUINoBlock(false);
}
};
dashboardData = result;
processOutData(r);
}
});
}
}
private String callService(String serviceName, List<NameValuePair> params) {
String result = ws.callService(serviceName, params);
return result;
}
private void processOutData(final Runnable rAfterProcessing) {
if (dashboardData == null || dashboardData.length() == 0)
return;
new Thread() {
#Override
public void run() {
super.run();
final List<HashMap<String, String>> dataList = XMLfunctions
.getDataList(dashboardData, new String[] { XT.MODE,
XT.DATE, XT.USER_COUNT, XT.TOT_LOGIN_TIME,
XT.TOT_PICK_ITEM_COUNT, XT.AVG_PICKING_SPEED });
final List<DasDetails> tempList = new ArrayList<DasDetails>();
for (int i = 0; i < dataList.size(); i++) {
int pos = docExists(tempList, dataList.get(i).get(XT.MODE));
if (pos == -1) {
if (SEARCH_TYPE == 0
|| KEYWORD.equals("")
|| (SEARCH_TYPE == 1 && dataList.get(i)
.get(XT.CUST_NAME).contains(KEYWORD))
|| (SEARCH_TYPE == 2 && dataList.get(i)
.get(XT.DOC_NO).contains(KEYWORD))) {
DasDetails doc = new DasDetails(dataList.get(i));
int cachePos = getPosInCachedCounterUpdates(doc.cMode);
if (cachePos != -1) {
if (cachedCounterUpdates.get(cachePos)[1]
.equals(doc.dDate))
cachedCounterUpdates.remove(cachePos);
else
doc.dDate = cachedCounterUpdates
.get(cachePos)[1];
}
tempList.add(doc);
pos = tempList.size() - 1;
}
}
if (pos == -1)
continue;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
docList = tempList;
rAfterProcessing.run();
logit("processOutData", "Processing OVER");
}
});
for (int i = 0; i < docList.size(); i++) {
itemsTotal = itemsTotal+ Integer.parseInt(docList.get(i).totPickItemCount);
userTotal = userTotal + Integer.parseInt(docList.get(i).userCount);
totalTime = totalTime + Integer.parseInt(docList.get(i).totLoginTime);
}
System.out.println("PerformanceDashboard.processOutData() -- fINAL item TOTAL " + itemsTotal); // 6 i have data here but i need this data in my oncreate but not getting why?????
System.out.println("PerformanceDashboard.processOutData() -- userTotal TOTAL " + userTotal); //4
System.out.println("PerformanceDashboard.processOutData() -- totalTime TOTAL " + totalTime); //310
noOfItems.setText(itemsTotal); // crashing with null pointer exception
// userCount.setText(userTotal);
// totalLoginTime.setText(totalTime);
};
}.start();
}
private class DasDetails {
public String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public DasDetails(HashMap<String, String> data) {
cMode = data.get(XT.MODE);
dDate = data.get(XT.DATE);
userCount = data.get(XT.USER_COUNT);
totLoginTime = data.get(XT.TOT_LOGIN_TIME);
totPickItemCount = data.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = data.get(XT.AVG_PICKING_SPEED);
}
}
public Integer docExists(List<DasDetails> list, String docNo) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).cMode.equals(docNo))
return i;
}
return -1;
}
private int getPosInCachedCounterUpdates(String docNo) {
for (int i = 0; i < cachedCounterUpdates.size(); i++) {
if (cachedCounterUpdates.get(i)[0].equals(docNo))
return i;
}
return -1;
}
}
This is the above code please go through it and let me know if any clarifications are required. I cannot able to set "itemsTotal" value to "noOfIttems" textview. I have added the comments. Please help me in solving this issue.
Thanks in advance.
Please check your noOfItems textView's id. TextView is null.
I'm hosting a server on my raspberry pi 2, and sending a stream of values between 0 and 360. I'm trying to grab whatever number is just sent on my android phone. Currently, it runs through the ReadServer code once, returns 48 (char 0) and then crashes with an 'unhandled runtime exception'. I'm able to just dummy values and have it work perfectly fine, so I know its something having to do with the client/server side.
Yes I have internet permission specified in my manifest.
PI
Server hosted on raspberry pi 2:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
void error(char * msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, clisockfd, portno = 5003;
socklen_t clilen;
char buffer[127];
struct sockaddr_in serv_addr, cli_addr;
int n;
/* call socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) { error("ERROR opening socket"); }
/* initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
printf("waiting to bind\n");
fflush(stdout);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{ error("ERROR on binding"); }
listen(sockfd, 5);
clilen = (socklen_t) sizeof(cli_addr);
printf("waiting to accept\n");
clisockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
printf("accepted\n");
if (clisockfd < 0) { error("ERROR on accept"); }
int heading = 0;
while (heading < 360)
{
bzero(buffer, 126);
printf("sending\n");
sprintf(buffer, "%d\n", heading);
n = write(clisockfd, buffer, strlen(buffer));
if (n < 0) { error("ERROR writing to socket"); }
printf("sending %s\n", buffer);
usleep(2 * 1000*1000);
heading = heading + 2;
}
close(sockfd);
return 0;
}
ANDROID
Main activity code:
public class MainActivity extends AppCompatActivity {
final String IP_ADDRESS = "x.x.x.x"; // (is an actual address)
final int PORT = 5003;
boolean isManual = true;
RelativeLayout layout_joystick;
JoyStickClass js;
TextView velocityTextView;
Button manualButton;
ImageView compassPhoto;
Wifi wifiController;
ReadServer serverObject;
Timer serverTimer = new Timer();
Handler serverPollHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set new view
setContentView(R.layout.activity_main);
// define buttons/interactions
manualButton = (Button) findViewById(R.id.manual_button);
Button disconnectButton = (Button) findViewById(R.id.disconnect_button);
layout_joystick = (RelativeLayout) findViewById(R.id.layout_joystick);
compassPhoto = (ImageView) findViewById(R.id.imageViewCompass);
// set joystick settings
js = new JoyStickClass(getApplicationContext()
, layout_joystick, R.drawable.image_button);
js.setStickSize(150, 150);
js.setLayoutSize(500, 500);
js.setLayoutAlpha(150);
js.setStickAlpha(90);
js.setOffset(90);
js.setMinimumDistance(50);
// set button listeners
manualButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
toggleMode();
}
});
layout_joystick.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
return jsOnTouchListener(arg0, arg1);
}
});
disconnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
switchToLoadScreen(view);
}
});
// load camera feed
WebView wv = (WebView)findViewById(R.id.webView);
velocityTextView = (TextView) findViewById(R.id.velocityText);
serverPollHandler = new Handler(serverCallback);
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
//connect wifi
wifiController = new Wifi(IP_ADDRESS, PORT);
if (!wifiController.Connect()){
switchToLoadScreen(findViewById(android.R.id.content));
}
serverObject = new ReadServer(wifiController.getInputStream());
serverTimer.scheduleAtFixedRate(new getFromServer(), 500, 2 * 1000);
}
});
wv.loadUrl("file:///android_asset/cameraFeed.html");
}
Handler.Callback serverCallback = new Handler.Callback() {
public boolean handleMessage(Message msg) {
velocityTextView.setText("1m/s");
try {
serverObject.execute().get();
int headingToMoveTo = serverObject.getHeading();
moveCompassTo(headingToMoveTo);
}
catch (InterruptedException e) {}
catch (ExecutionException e) {}
return true;
}
};
// move the compass
private void moveCompassTo(float degree) {
float currentDegree = 0f;
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(
currentDegree,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
ra.setDuration(5);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
compassPhoto.startAnimation(ra);
int a = 5;
}
// toggle between manual and autonomous modes
private void toggleMode() {
if (isManual) {
// set Autonomous Mode
manualButton.setText(R.string.manual_text);
layout_joystick.setVisibility(View.INVISIBLE);
wifiController.enterAutonomous();
isManual = false;
} else {
// set Manual Mode
manualButton.setText(R.string.autonomous_text);
layout_joystick.setVisibility(View.VISIBLE);
wifiController.enterManual();
isManual = true;
}
}
// switch between views
private void switchToLoadScreen(View thisView) {
if (wifiController.Disconnect()) {
serverTimer.cancel();
Intent myIntent = new Intent(thisView.getContext(), LoadScreen.class);
startActivityForResult(myIntent, 0);
}
}
// control what moving the joystick does {emitted}
private boolean jsOnTouchListener(View arg0, MotionEvent arg1) {
js.drawStick(arg1);
if (arg1.getAction() == MotionEvent.ACTION_DOWN
|| arg1.getAction() == MotionEvent.ACTION_MOVE) {
// textView1.setText("X : " + String.valueOf(js.getX()));
// textView2.setText("Y : " + String.valueOf(js.getY()));
// textView3.setText("Angle : " + String.valueOf(js.getAngle()));
// textView4.setText("Distance : " + String.valueOf(js.getDistance()));
switch (js.get8Direction()){
case JoyStickClass.STICK_UP:
wifiController.moveForward();
break;
case JoyStickClass.STICK_UPRIGHT:
wifiController.moveForwardRight();
break;
case JoyStickClass.STICK_RIGHT:
wifiController.moveRight();
break;
case JoyStickClass.STICK_DOWNRIGHT:
wifiController.moveBackRight();
break;
case JoyStickClass.STICK_DOWN:
wifiController.moveBack();
break;
case JoyStickClass.STICK_DOWNLEFT:
wifiController.moveBackLeft();
break;
case JoyStickClass.STICK_LEFT:
wifiController.moveLeft();
break;
case JoyStickClass.STICK_UPLEFT:
wifiController.moveForwardLeft();
break;
case JoyStickClass.STICK_NONE: // center
break;
}
} else if (arg1.getAction() == MotionEvent.ACTION_UP) {
// textView1.setText("X :");
// textView2.setText("Y :");
// textView3.setText("Angle :");
// textView4.setText("Distance :");
// textView5.setText("Direction :");
}
return true;
}
public class getFromServer extends TimerTask {
public void run() {
serverPollHandler.sendEmptyMessage(0);
}
}
}
ReadServer code:
public class ReadServer extends AsyncTask {
BufferedReader thisStream;
int heading = 0;
public ReadServer(BufferedReader fromPi)
{
thisStream = fromPi;
}
public int getHeading() {
return heading;
}
#Override
protected Object doInBackground(Object[] params) {
//communication from PI
try {
if (thisStream.ready()) {
int read = thisStream.read();
String t = Character.toString ((char) read);
if (read > 0) {
heading = Integer.parseInt(t);
}
}
}
catch (IOException e) {}
return params;
}
}
WifiController code:
public class Wifi extends AsyncTask {
// THESE MUST BE IDENTICAL TO THE PI CODE FOR CORRECT FUNCTIONALITY
private enum send_modes {
AUTONOMOUS_FLAG,
MANUAL_FLAG,
DISCONNECT_PI,
MOVE_NORTH,
MOVE_NORTHEAST,
MOVE_EAST,
MOVE_SOUTHEAST,
MOVE_SOUTH,
MOVE_SOUTHWEST,
MOVE_WEST,
MOVE_NORTHWEST
}
//
private Socket phoneToPiSocket;
private boolean isConnected = false;
private InetAddress piIPAddress;
private PrintWriter piSocketWriter;
private int portNumber;
private BufferedReader fromPi;
public Wifi(String ipAddr, int port) {
try {
portNumber = port;
piIPAddress = InetAddress.getByName(ipAddr);
} catch (UnknownHostException e) {
piIPAddress = null;
}
}
#Override
protected Object doInBackground(Object[] params) {
try {
phoneToPiSocket = new Socket(piIPAddress, portNumber);
fromPi = new BufferedReader(new InputStreamReader (phoneToPiSocket.getInputStream()));
// piSocketWriter = new PrintWriter(phoneToPiSocket.getOutputStream(), true);
isConnected = true;
} catch (ConnectException e) {
isConnected = false;
} catch (UnknownHostException e) {
isConnected = false;
} catch (IOException e) {
isConnected = false;
}
return params;
}
public boolean Disconnect() {
if (isConnected) {
try {
fromPi.close();
//disconnectFromPi(); // has to happen before writer is closed!
//piSocketWriter.close();
phoneToPiSocket.close();
isConnected = false;
} catch (IOException e) {
return false;
}
}
return true;
}
public BufferedReader getInputStream()
{
return fromPi;
}
public boolean Connect() {
// set up wifi connection
try {
execute().get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
if (isConnected) {
return true;
} else {
return false;
}
}
boolean isConnected(){
return isConnected;
}
//communication to PI
public void enterAutonomous()
{
piSocketWriter.println(send_modes.AUTONOMOUS_FLAG.ordinal());
}
public void enterManual()
{
piSocketWriter.println(send_modes.MANUAL_FLAG.ordinal());
}
public void disconnectFromPi()
{
piSocketWriter.println(send_modes.DISCONNECT_PI.ordinal());
}
public void moveForward()
{
piSocketWriter.println(send_modes.MOVE_NORTH.ordinal());
}
public void moveForwardRight()
{
piSocketWriter.println(send_modes.MOVE_NORTHEAST.ordinal());
}
public void moveRight()
{
piSocketWriter.println(send_modes.MOVE_EAST.ordinal());
}
public void moveBackRight()
{
piSocketWriter.println(send_modes.MOVE_SOUTHEAST.ordinal());
}
public void moveBack()
{
piSocketWriter.println(send_modes.MOVE_SOUTH.ordinal());
}
public void moveBackLeft()
{
piSocketWriter.println(send_modes.MOVE_SOUTHWEST.ordinal());
}
public void moveLeft()
{
piSocketWriter.println(send_modes.MOVE_WEST.ordinal());
}
public void moveForwardLeft()
{
piSocketWriter.println(send_modes.MOVE_NORTHWEST.ordinal());
}
}
I apologize for how messy / horribly named everything is. Its a work in progress.
Thanks for the help.
UPDATED INFO:
The exception i get is:
"main#20747" prio=5 waiting
java.lang.Thread.State: WAITING
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:72)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
Picture of frames at crash
This is how I am trying to execute my code.
private final class BoxSelect implements View.OnTouchListener
{
public boolean onTouch(View view, MotionEvent motionEvent)
{
setView(view);
setMotionEvent(motionEvent);
if (t1.getState() == Thread.State.NEW)
{
t1.start();
if (getHit() == false) {
t2.start();
}
}
return false;
}
}
I have two thread created called t1 and t2 which take the two runnable methods r1 and r1 as parameters:
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
R1 is defined as:
Runnable r1 = new Runnable() {
public void run() {
System.out.println("ENTERING RUN t1");
class BoxSelect implements View.OnTouchListener {
Drawable hitTarget = getResources().getDrawable(R.drawable.hit);
Drawable missTarget = getResources().getDrawable(R.drawable.miss);
View view1 = getView();
MotionEvent motionEvent1 = getMotionEvent();
public void whenCreate()
{
System.out.println("HERE t1");
hit = false;
boolean goToElse = true;
boolean hit2 = false;
boolean goToElse2 = true;
if (motionEvent1.getAction() == MotionEvent.ACTION_DOWN) {
for (int i = 0; i < ids.length; i++) {
for (int j = 0; j < ids.length; j++) {
String coord = b.getBoard()[i][j];
if (view == ids[i][j]) {
System.out.println("ATTACKING " + b.getCompTempBoard()[i][j]);
player.basicAttack(b.getBoard(), coord, ai);
}
if (view == ids[i][j] && b.getCompTempBoard()[i][j].equalsIgnoreCase("HIT")) {
System.out.println("Hit GUI");
if (ids[i][j].getBackground().equals(hitTarget)) {
hit = true;
goToElse = false;
} else {
ids[i][j].setBackgroundDrawable(hitTarget);
System.out.println("ert 1 " + b.getCompTempBoard()[i][j]);
playerCount++;
if (playerCount == 10) {
player.endGame();
b.incrementPlayerCount();
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("YOU WIN :)\nScore is:\nPlayer: " + b.getPlayerWinCount() + "\nComputer: " + b.getCompWinCount());
builder1.setCancelable(true);
builder1.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(AttackShips6.this, MainMenu.class);
startActivity(intent);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
for (int k = 0; k < ids2.length; k++) {
for (int r = 0; r < ids2.length; r++) {
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getCompTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getCompTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids[k][r].setBackgroundDrawable(missTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids2[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids2[k][r].setBackgroundDrawable(missTarget);
}
}
}
}
hit = true;
goToElse = false;
}
} else if (view == ids[i][j] && b.getCompTempBoard()[i][j].equalsIgnoreCase("MISS")) {
System.out.println("MISS GUI 1");
if (ids[i][j].getBackground().equals(missTarget)) {
hit = true;
goToElse = false;
} else {
System.out.println("MISS GUI");
ids[i][j].setBackgroundDrawable(missTarget);
System.out.println("ert 2 " + b.getCompTempBoard()[i][j]);
hit = true;
goToElse = true;
}
}
if (goToElse == true) {
hit = false;
System.out.println("MISS PLAYER GUI");
view.setBackgroundDrawable(missTarget);
}
}
}
}
}
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
}
}
};
and R2 is:
Runnable r2 = new Runnable() {
public void run() {
System.out.println("ENTERING RUN t2");
try {
TimeUnit.NANOSECONDS.sleep(1);
System.out.println("HERE 2");
class BoxSelect implements View.OnTouchListener {
Drawable hitTarget = getResources().getDrawable(R.drawable.hit);
Drawable missTarget = getResources().getDrawable(R.drawable.miss);
public boolean onTouch(View view, MotionEvent motionEvent) {
System.out.println("HERE t2");
if (hit == false) {
System.out.println("SLEEPING 2");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("COMPUTERS TURN");
ai.advancedAttack(b.getBoard(), ai.getRandomCoordinate_For_Attacking_6x6(), player);
System.out.println("First attack: " + ai.getFirstCoord());
boolean goAgain = true;
while (goAgain == true) {
for (int w = 0; w < ids2.length; w++) {
for (int y = 0; y < ids2.length; y++) {
if (b.getBoard()[w][y].equalsIgnoreCase(ai.getFirstCoord()) && b.getTempBoard()[w][y].equalsIgnoreCase("HIT")) {
System.out.println("DR 1");
ids2[w][y].setBackgroundDrawable(hitTarget);
ai.setFirstCoord(ai.getNextCoordToAttack());
System.out.println("Next: " + ai.getFirstCoord());
ai.advancedAttack(b.getBoard(), ai.getFirstCoord(), player);
System.out.println("After attack in loop");
goAgain = true;
CompCount++;
if (CompCount == 10) {
b.incrementCompCount();
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("YOU LOSE :(\n" + "Score is:\n" + "Player: \n" + b.getPlayerWinCount() + "\nComputer: " + b.getCompWinCount());
builder1.setCancelable(true);
builder1.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(AttackShips6.this, MainMenu.class);
startActivity(intent);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
for (int k = 0; k < ids2.length; k++) {
for (int r = 0; r < ids2.length; r++) {
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getCompTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getCompTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids[k][r].setBackgroundDrawable(missTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids2[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids2[k][r].setBackgroundDrawable(missTarget);
}
}
}
}
} else if (b.getBoard()[w][y].equalsIgnoreCase(ai.getFirstCoord()) && b.getTempBoard()[w][y].equalsIgnoreCase("MISS")) {
System.out.println("DR 2");
ids2[w][y].setBackgroundDrawable(missTarget);
ai.setFirstCoord(ai.getNextCoordToAttack());
goAgain = false;
}
}
}
}
}
return hit;
}
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
System.out.println("IN CATCH");
}
System.out.println("END");
}
};`
I originally had these two together as one block, but separated it as I wish to pause thread 2 from occurring for one second after thread 2.
The problem I am having is that the BoxSelect class is not getting executed inside the R1 and R2 and so none of the code is executing. Any help on this matter would be appreciated!