Android CounDownTimer.cancel() not working - java

I'm trying make a serial IEC communication for Android and there I need check if a device send some data. I started a timer on the begin of communication a reset it when some data comes. Reset on incoming data is working, but cancelling before data is saved not working. I can't understand why.
Here is my MainActivity.java code
package cz.trisko.jan.amr;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbDeviceConnection;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import static java.lang.Integer.parseInt;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "AMR";
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialDevice;
private String handshake = "/?!\r\n";
MediaPlayer errSnd; // chyba
MediaPlayer bdSnd; // registry
MediaPlayer lpSnd; // profil
MediaPlayer infoSnd; // info
ProgressBar progressBar;
RadioGroup rg;
RadioButton rb;
TextView registryNam; // textview pro nazev registru
TextView registryVal; // textview pro hodnotu registru a stavova hlaseni
String regName; // nazev registru
String regValue; // hodnota registru
boolean readRegs; // typy odectu
boolean readLastMonth;
boolean readThisMonth;
Calendar calendar = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyMMdd");
int currentMonth;
int currentYear;
Date today;
Date tomorrow;
String tomorrowAsString;
String lastMonthInterval;
String thisMonthInterval;
String lpInterval;
int startMonth;
int startYear;
int endMonth;
int endYear;
private static final Pattern communicationSpeedIndexPattern
= Pattern.compile("^.*(/)(\\w{3})(\\d{1})(.*)$"); // [0] - komplet, [1] - /, [2] - vyrobce, [3] - baudrate, [4] - model
private static final Pattern CRpat = Pattern.compile("^(\r)$"); // CR
private static final Pattern LFpat = Pattern.compile("^(\n)$"); // LF
private static final Pattern STXpat = Pattern.compile("^(\\x02)$"); // STX
private static final Pattern ETXpat = Pattern.compile("^(\\x03)$"); // ETX
private static final Pattern DLEpat = Pattern.compile("^(\\x10)$"); // DLE
private static final Pattern ETBpat = Pattern.compile("^(\\x17)$"); // ETB
private static final Pattern regNameValuePattern
= Pattern.compile("([^\\(\\)]*)\\(([^\\(\\)]*)\\)"); // [0] - komplet, [1] - Registr, [2] - hodnota
boolean CRLF; // konec radku prijimanych dat
boolean isCR;
boolean isLF;
boolean firstLine;
boolean isETX;
String data; // prichozi data na USB
String dataLine; // radek s prichozimi daty
String tmpDataLine; // radek prichozich dat, ktery je zpracovavan po znacich
//String tmpDataLine2; // radek prichozich dat, ktery je zpracovavan po znacich
String buffer; // buffer pro vystup do souboru
//String tmpBuffer = "";
int dataLength;
private int[] baudrateList = {300, 600, 1200, 2400, 4800, 9600, 19200};
String meterId;
Pattern meterIdPattern = Pattern.compile("0\\.0\\.0|0\\.0|0|C\\.1|C\\.1\\.0|0\\.0\\.1|0\\.0\\.2|0\\.0\\.3|C\\.1\\.1|C\\.90\\.1");
int speed; // komunikacni rychlost seriove link - pocatek 300 Bd
int readedSpeed; // maximalni komunikacni rychlost v zarizeni
String askData; // retezec pro odeslani pozadavku dat
char valueSOHchar = 0x01; // SOH
String SOH = String.valueOf(valueSOHchar);
char valueSTXchar = 0x02; // STX
String STX = String.valueOf(valueSTXchar);
char valueETXchar = 0x03; // ETX
String ETX = String.valueOf(valueETXchar);
char valueACKchar = 0x06; // ACK
String ACK = String.valueOf(valueACKchar);
char valueDLEchar = 0x10; // DLE
String DLE = String.valueOf(valueDLEchar);
char valueNAKchar = 0x15; // NAK
String NAK = String.valueOf(valueNAKchar);
char valueETBchar = 0x17; // ETB
String ETB = String.valueOf(valueETBchar);
int etxIndex; // pocet prichozich ETX
boolean registryReceived;
String filename;
String filepath;
File myExternalFile;
boolean successCreateDir;
boolean outputDirOk;
boolean meterEchoes;
//String debugStringValue = "";
long startTime;
long currentTime;
long timeLeft;
MyTimer responseTimeCounter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "-------------- APP START --------------");
setDates(); // nastavime intervaly odectu
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
errSnd = MediaPlayer.create(this, R.raw.wrong);
bdSnd = MediaPlayer.create(this, R.raw.case_closed);
lpSnd = MediaPlayer.create(this, R.raw.beep_beep_beep);
infoSnd = MediaPlayer.create(this, R.raw.smack_that_bitch);
rg = findViewById(R.id.readoutType);
registryNam = findViewById(R.id.registryNames);
registryVal = findViewById(R.id.registryValues);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
// casovac pro prodlevu na vstupu
responseTimeCounter = new MyTimer(5000,1);
}
public void setDefaultValues() {
// nastaveni vychozich polozek pro odecet
regName = "";
regValue = "";
readRegs = false;
readLastMonth = false;
readThisMonth = false;
CRLF = false; // konec radku prijimanych dat
isCR = false;
isLF = false;
firstLine = true; // nacitani prvniho radku dat
isETX = false;
data = null; // prichozi data na USB
dataLine = ""; // radek s prichozimi daty
tmpDataLine = ""; // radek prichozich dat, ktery je zpracovavan po znacich
buffer = ""; // buffer pro vystup do souboru
dataLength = 0;
meterId = "";
speed = 300; // komunikacni rychlost - pocatek 300 Bd
readedSpeed = 0; // index komunikacni rychlosti nacteny ze zarizeni
askData = ""; // retezec pro odeslani pozadavku dat
tvSetContent(registryNam, "");
tvSetContent(registryVal, "");
meterEchoes = false;
registryReceived = false;
etxIndex = 0;
}
public String toHex(String arg) {
return String.format("%012x", new BigInteger(1, arg.getBytes()));
}
public void setDates() {
// vypocet dat pro interval odectu
String leadingStartMonthZero = "";
String leadingEndMonthZero = "";
String startDate;
String endDate;
currentMonth = calendar.get(Calendar.MONTH) + 1;
currentYear = calendar.get(Calendar.YEAR) % 100;
// dnes / today
today = calendar.getTime();
// zitra / tomorrow
calendar.add(Calendar.DAY_OF_YEAR, 1);
tomorrow = calendar.getTime();
dateFormat = new SimpleDateFormat("yyMMdd");
tomorrowAsString = dateFormat.format(tomorrow);
// interval pro odecet pri vymene - od 1. tohoto mesice do zitra / this month
if (currentMonth < 10) {
leadingStartMonthZero = "0";
}
startDate = "0" + currentYear + leadingStartMonthZero + currentMonth + "010000";
endDate = "0" + tomorrowAsString + "0000";
thisMonthInterval = startDate + ";" + endDate;
// interval pro std odecet - od 1. minuleho mesice do 1. tohoto mesice / last month
startYear = currentYear;
endYear = currentYear;
startMonth = currentMonth - 1;
endMonth = currentMonth;
if (currentMonth == 1) {
startYear = currentYear - 1;
startMonth = 12;
endYear = currentYear;
endMonth = currentMonth;
}
if (endMonth < 10) {
leadingEndMonthZero = "0";
}
if (startMonth < 10) {
leadingStartMonthZero = "0";
}
startDate = "0" + startYear + leadingStartMonthZero + startMonth + "010000";
endDate = "0" + endYear + leadingEndMonthZero + endMonth + "010000";
lastMonthInterval = startDate + ";" + endDate;
}
private boolean checkUSBdevice() {
boolean pass = false;
Map<String, UsbDevice> deviceList = usbManager.getDeviceList();
if (deviceList.isEmpty()) {
pass = false;
} else {
for (Map.Entry<String, UsbDevice> entry : deviceList.entrySet()) {
device = entry.getValue();
if (usbManager.hasPermission(device)) {
Log.d(TAG, "USB has permission");
pass = true;
} else {
Toast.makeText(getApplicationContext(), "Není oprávnění pro přístup k USB zařízení", Toast.LENGTH_LONG).show();
errSnd.start(); // chck OK
Log.d(TAG, "USB have not permission");
pass = false;
}
}
}
if (pass) {
return true;
} else {
return false;
}
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
} else {
return false;
}
}
public void getReadoutType() {
String selectedtext = (String) rb.getText();
int radioButtonID = rg.getCheckedRadioButtonId();
View radioButton = rg.findViewById(radioButtonID);
int rbIndex = rg.indexOfChild(radioButton);
switch (rbIndex) {
case 0: // odecet jen registru
readRegs = true;
readLastMonth = false;
readThisMonth = false;
break;
case 1: // odecet registru a LP za minuly mesic
readRegs = true;
readLastMonth = true;
readThisMonth = false;
break;
case 2: // odecet registru a LP za tent mesic
readRegs = true;
readLastMonth = false;
readThisMonth = true;
break;
}
Log.d(TAG, "Index radiobuttonu: " + rbIndex + " - " + selectedtext);
Log.d(TAG, "readRegs = " + readRegs);
Log.d(TAG, "readLastMonth = " + readLastMonth);
Log.d(TAG, "readThisMonth = " + readThisMonth);
}
private void tvSetContent(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override public void run() {
ftv.setText(ftext);
}
});
}
public void getSpeed() throws InterruptedException {
// nacteni rychlostniho indexu z identifikacniho retezce / get device max speed
Matcher speedIndex = communicationSpeedIndexPattern.matcher(tmpDataLine);
Log.d(TAG, "getSpeed processing");
if (speedIndex.find()) {
readedSpeed = parseInt(speedIndex.group(3));
Log.d(TAG, "Speed index " + readedSpeed);
speed = baudrateList[readedSpeed];
Log.d(TAG, "New speed will be " + speed + " Bd");
tvSetContent(registryVal, "Komunikace na " + speed + " Bd");
if (readThisMonth || readLastMonth) {
askData = ACK + "0" + readedSpeed + "1\r\n";
Log.d(TAG, "Profile ACK");
} else {
askData = ACK + "0" + readedSpeed + "0\r\n";
Log.d(TAG, "Registry ACK");
}
Log.d(TAG, "Waiting 300 ms");
Thread.sleep(300);
Log.d(TAG, "Send to serial " + askData + "|" + toHex(askData));
serialDevice.write(askData.getBytes());
Log.d(TAG, "Waiting 300 ms");
Thread.sleep(300);
Log.d(TAG, "Serial line switching to " + speed + " Bd");
serialDevice.setBaudRate(speed);
Log.d(TAG, "Speed switched");
} else {
Log.d(TAG, "No speed index found");
}
}
public void showValues() {
// rozlozeni na nazev a hodnotu registru / show registry name and value
Matcher regNamVal = regNameValuePattern.matcher(tmpDataLine);
if (regNamVal.find()) {
regName = regNamVal.group(1).toString();
regValue = regNamVal.group(2).toString();
tvSetContent(registryNam, regName);
tvSetContent(registryVal, regValue);
if (meterId == "") {
// hledame cislo elektromeru / looking for meter ID
Matcher metId = meterIdPattern.matcher(regName);
if (metId.matches()) {
meterId = regValue;
Log.d(TAG, "meterId = " + meterId);
}
}
} else {
tvSetContent(registryVal, tmpDataLine);
Log.d(TAG, "Pickup registry and value fail");
tvSetContent(registryNam, "");
tvSetContent(registryVal, "");
}
}
public void chkDirectories() {
// kontrola/vytvoreni adresaru pro vystup a konfiguraci / chck output dir
outputDirOk = false;
File dirDocuments = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
String dirDocumentsPath = dirDocuments.getPath();
File dirAmr = new File(dirDocumentsPath+"/AMR");
filepath = dirAmr.getAbsolutePath();
if (!dirAmr.exists()) {
// adresar pro vystup neexistuje, vytvorime ho
successCreateDir = dirAmr.mkdir();
if (successCreateDir) {
Log.d(TAG,"Directory " + filepath + " created successfully");
} else {
Log.d(TAG,"Creating od directory " + filepath + " FAILED!");
}
} else {
Log.d(TAG,"AMR directory OK");
File dirReadouts = new File(filepath + "/Readouts");
filepath = dirReadouts.getAbsolutePath();
if (!dirReadouts.exists()) {
successCreateDir = dirReadouts.mkdir();
if (successCreateDir) {
outputDirOk = true;
Log.d(TAG,"Directory " + filepath + " created successfully");
} else {
Log.d(TAG,"Creating od directory " + filepath + " FAILED!");
}
} else {
outputDirOk = true;
Log.d(TAG,"Readouts directory OK");
}
}
Log.d(TAG,"Readouts output directory: " + filepath);
}
public void saveFile() {
// ukladame na SD kartu / saving to SD
try {
tvSetContent(registryVal, "Ukládám data" + filename);
Log.d(TAG, "Timer pred ukladanim: " + timeLeft);
responseTimeCounter.cancel(); // zastavime casovac odezvy elektromeru / cancel timer
/* THIS CANCEL DID NOT WORKING - WHY???????????????????????? */
Log.d(TAG, "Timer po jeho preruseni: " + timeLeft);
filename = meterId.trim() + ".rd";
myExternalFile = new File(filepath, filename);
Log.d(TAG,"Output stream start " + myExternalFile.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(myExternalFile);
Log.d(TAG, "Start writting data");
fos.write(buffer.getBytes());
Log.d(TAG, "Closing file - saved to " + myExternalFile.getAbsolutePath());
fos.close();
tvSetContent(registryVal, "Uloženo do " + filename);
Log.d(TAG, "Closing serial communication");
connection.close();
bdSnd.start();
} catch (IOException e) {
e.printStackTrace();
}
// ukladame do interniho uloziste / saving in to internal storage
/*
try {
filename = meterId.trim() + ".rd";
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+filename)));
bufferedWriter.write(buffer);
bufferedWriter.close();
tvSetContent(registryVal, "Uloženo do " + filename);
//setDefaultValues();
bdSnd.start();
} catch (IOException e) {
e.printStackTrace();
}
*/
}
public void processData() throws InterruptedException {
// prochazeni prichozich dat po znacich
for (dataLength = 0; dataLength < data.length(); dataLength++) {
//Process char
char c = data.charAt(dataLength);
String charToString = c + "";
Log.d(TAG, "R <- " + charToString + " hex:" + toHex(charToString));
Matcher incomingOneChar = STXpat.matcher(charToString);
if (incomingOneChar.matches()) {
Log.d(TAG, "\n\nSTX found - dropping it\n\n");
charToString = ""; // drop STX char
}
Matcher nextIncomingOneChar = ETXpat.matcher(charToString);
if (nextIncomingOneChar.matches()) {
Log.d(TAG, "\n\nETX found - dropping it and next data\n\n");
charToString = ""; // drop ETX char a vsechno za tim
isETX = true;
etxIndex += 1;
dataLength = data.length(); // ukonci cyklus driv
registryReceived = true;
responseTimeCounter.cancel();
saveFile();
}
// je prichozi znak CR?
Matcher incomingCharCR = CRpat.matcher(charToString);
if (incomingCharCR.matches()) {
//tvAppend(textView, "CR");
isCR = true;
//Log.d(TAG, "CR");
} else {
// je prichozi znak LF?
Matcher incomingCharLF = LFpat.matcher(charToString);
if (incomingCharLF.matches()) {
//tvAppend(textView, "LF");
isLF = true;
//Log.d(TAG, "LF");
}
}
tmpDataLine += charToString; // pridame nacteny znak do radku
// reset casovace na vstupu
responseTimeCounter.cancel();
responseTimeCounter.start();
/* THIS TIMER RESET WORKING */
if (isCR && isLF) {
// je konec radku?
CRLF = true;
}
if (CRLF) {
// mame cely radek, zpracujeme jej / processing completed data row
//Log.d(TAG, "CRLF");
if (firstLine) {
// v prvnim radku je identifikace s indexem rychlosti
Log.d(TAG, "First line completed - " + tmpDataLine);
if (tmpDataLine.equals(handshake)) {
// test na echo
meterEchoes = true;
tmpDataLine = ""; // drop radku s echem
Log.d(TAG, "Meter send echo");
} else {
getSpeed();
firstLine = false;
Log.d(TAG, "First line operated");
}
}
if (meterEchoes && tmpDataLine.equals(askData)) {
// pokud elektromer vraci echo, drop data
tmpDataLine = "";
}
buffer += tmpDataLine;
Log.d(TAG, "tmpDataLine: " + tmpDataLine);
if (!tmpDataLine.equals("")) {
// pokud nejaka data jsou, zobraz je
showValues();
}
dataLine = ""; // vymazeme obsah radku
CRLF = false;
isCR = false;
isLF = false;
tmpDataLine = "";
}
}
}
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
//Defining a Callback which triggers whenever data is read.
//#TargetApi(Build.VERSION_CODES.KITKAT)
//#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onReceivedData(byte[] arg0) {
//String data = null;
try {
data = new String(arg0);
//Log.d(TAG, "R <- " + data);
Log.d(TAG, "Timer pri vstupu dat na USB: " + timeLeft);
processData();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private void startSerialConnection(UsbDevice device) {
Log.i(TAG, "Ready to open USB device connection");
connection = usbManager.openDevice(device);
serialDevice = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialDevice != null) {
if (serialDevice.open()) {
serialDevice.setBaudRate(speed);
serialDevice.setDataBits(UsbSerialInterface.DATA_BITS_7);
serialDevice.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialDevice.setParity(UsbSerialInterface.PARITY_EVEN);
serialDevice.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
Log.d(TAG, "mCallback Called");
serialDevice.read(mCallback);
Log.d(TAG, "Serial connection opened at " + speed + " Bd");
} else {
Log.d(TAG, "Cannot open serial connection");
tvSetContent(registryVal, "Nefunguje COM port");
Toast.makeText(getApplicationContext(), "Nefunguje COM port", Toast.LENGTH_LONG).show();
infoSnd.start();
}
} else {
Log.d(TAG, "Could not create USB Serial Device");
}
}
public class MyTimer extends CountDownTimer {
public MyTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
tvSetContent(registryNam, String.valueOf(millisUntilFinished));
}
#Override
public void onFinish() {
errSnd.start();
tvSetContent(registryVal, "Elektroměr neodpovídá"); // device did not respond
connection.close();
}
}
public void doReadout(View view) {
setDefaultValues();
chkDirectories();
int radioButtonId = rg.getCheckedRadioButtonId();
rb = findViewById(radioButtonId);
Log.d(TAG, "Do Readout pressed");
if (!isExternalStorageWritable()) {
Toast.makeText(getApplicationContext(), "Externí úložiště není k dispozici.", Toast.LENGTH_LONG).show();
errSnd.start();
}
// pro zapis na SD kartu
if (!outputDirOk) {
Toast.makeText(getApplicationContext(), "Adresář pro výstup není k dispozici.", Toast.LENGTH_LONG).show();
errSnd.start();
}
if (checkUSBdevice() && isExternalStorageWritable() && outputDirOk) {
startSerialConnection(device);
if (device != null) {
//tvSetContent(registryVal, "Sériová komunikace spuštěna");
Log.d(TAG, "Serial communication opened");
} else {
Log.d(TAG, "Serial communication opening FAIL");
}
if (rb == null) {
Toast.makeText(getApplicationContext(), "Není vybrán typ odečtu!", Toast.LENGTH_LONG).show();
Log.d(TAG, "No readout type selected");
errSnd.start();
} else {
getReadoutType();
tvSetContent(registryVal, "Posílam handshake");
serialDevice.write(handshake.getBytes());
Log.d(TAG, "Handshake sent " + toHex(handshake));
responseTimeCounter.start();
Log.d(TAG, "Response timer started");
}
} else {
// nepripojene USB nedelame nic
errSnd.start();
Toast.makeText(getApplicationContext(), "Není připojena USB optická sonda." ,Toast.LENGTH_LONG).show();
Log.d(TAG, "No USB device connected");
}
}
}

It depends whether you want your override of onFinish() to be called - generally it is not called on cancel() (but might be called on start()) so if you want the connection closed, call onFinish() after cancel()

I found the reason, why a timer did not want to be cancelled. There is .cancel() and .start() called in wrong place. They are called in cycle where is input processed char by char and there is too many cancels and starts in short time and that probably confused the timer. Moving timer restart out of this cycle solved my problem.

Related

Can ListView host TextView items that are also displayed in a separate TextView

I'm having a problem changing a TextView to a ListView. Originally, the app had a button that when clicked, runs tests to a bluetooth device and displays the results in a textview. I modified the app to contain two textviews that have the last text results and a separate xml file (connected with viewflipper) to go to a second textview that contains all of the test results, until the user clears the textview by clicking a button. I followed along with this example and checked what I was entering in the ArrayAdapter section of the code, and it appears to be what is required according to the developer's guide, but I still get his error:
Cannot resolve constructor 'ArrayAdapter(com.example.android.stardustscanner.ScannerFragment, int, int, java.lang.String)'
Why am I getting this error?
My .java file that I am making all the changes in is very long and contains a lot of thins that aren't relevant to this question and doesn't fit in the question box, so I'll try to only include the relevant parts. The error is towards the bottom with this line:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
ScannerFragment.java
public class ScannerFragment extends Fragment implements LocationListener {
ListView mListView;
//page switching things KG 8/24/17
private ViewFlipper mViewFlipper;
private float lastX;
private Button mViewLog;
private Button mReturnFlipper;
private TextView mShowData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.flipper_holder, container, false);//kg 8/24/17
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
SP = PreferenceManager.getDefaultSharedPreferences(getContext());
mViewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlip); //KG 8/24/17
mViewLog = (Button) view.findViewById(R.id.viewLog); //kg 8/24/17
mReturnFlipper = (Button) view.findViewById(R.id.flipperReturn); //kg 8/24/17
mShowData = (TextView) view.findViewById(R.id.textView) ; //kg 8/25/2017
mShowData.setText(readFromFile()); // kg 8/25/2017
mPowerOffButton = (Button) view.findViewById(R.id.button_poweroff);
mDisconnectButton = (Button) view.findViewById(R.id.button_disconnect);
mConnectButton = (Button) view.findViewById(R.id.button_connect);
mPresence = (Button) view.findViewById(R.id.button_present);
mBattery = (ProgressBar) view.findViewById(R.id.progressBar);
mBlinkConnect = (Button) view.findViewById(R.id.button_connectionblink);
mBlinkData = (Button) view.findViewById(R.id.button_communication);
mClearLog = (Button) view.findViewById(R.id.button_clear_log);
mDeviceName = (Button) view.findViewById(R.id.button_devicename);
mDeviceSN = (Button) view.findViewById(R.id.button_devicesn);
mBatteryPerc = (TextView) view.findViewById(R.id.label_batterypct);
mListView = (ListView) view.findViewById(R.id.scanLogView); //kg 8/28/17
// mReadingLog = (TextView) view.findViewById(R.id.scanLogView);
mReadingLog.setMovementMethod(new ScrollingMovementMethod());
mReadingLog.setText(readFromFile());
telephonyManager = (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
initLocationService(this.getContext());
final ActionBar actionBar = getActivity().getActionBar();
if (null == actionBar) {
return;
}
final Drawable D = getResources().getDrawable(R.drawable.stardust2);
actionBar.setBackgroundDrawable(D);
actionBar.setTitle("");
//KG 8/24/17
mViewLog.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showNext();
}
});
mReturnFlipper.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showPrevious();
}
});
}
private void setupScanner() {
Log.d(TAG, "setupScanner()");
// Initialize the send button with a listener that for click events
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isIris) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
} else {
publishMessage(Constants.COMMAND_POWEROFF);
}
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mDisconnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_DISCONNECT);
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mConnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_ON_CONNECT);
}
});
mClearLog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
mReadingLog.setText("");
if(SP.getBoolean("writeToFile", true)) {
writeToFile("", "", false);
}
}
});
// Initialize the ScannerService to perform bluetooth connections
mScannerService = new ScannerService(getActivity(), mHandler);
}
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
publishMessage(message);
}
return true;
}
};
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ScannerService.STATE_CONNECTED:
setStatus(mConnectedDeviceName);
if(mConnectedDeviceName.substring(0, 4).toLowerCase().equals("iris") || mConnectedDeviceName.substring(0, 8).toLowerCase().equals("stardust")) {
isIris = true;
mPresence.setClickable(true);
mPresence.setText("Click to detect taggant");
mPresence.setBackgroundColor(Color.parseColor("#0061ff"));
mPresence.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readoutStarted = true;
publishMessage(Constants.COMMAND_RUN_IRIS);
}
});
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
mScannerService.stop();
}
});
} else {
isIris = false;
}
if(!isIris) {
mPresence.setClickable(false);
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
publishMessage(Constants.COMMAND_ON_CONNECT);
timer = new Timer();
timerStarted = true;
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
publishMessage(Constants.COMMAND_READDATA);
}
}, 1000, 1000);
} else {
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
}
mBlinkConnect.setBackgroundColor(Color.parseColor("#11D901"));
break;
case ScannerService.STATE_CONNECTING:
setStatus("C");
break;
case ScannerService.STATE_LISTEN:
case ScannerService.STATE_NONE:
mBlinkConnect.setBackgroundColor(Color.parseColor("#ff2b0f"));
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
setStatus("D");
break;
}
break;
case Constants.MESSAGE_WRITE:
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
break;
case Constants.MESSAGE_READ:
mBlinkData.setBackgroundColor(Color.parseColor("#0091FA"));
String readMessage = (String)msg.obj;
if(isIris) {
readIris(readMessage);
} else {
readNormal(readMessage);
}
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
setupScanner();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
/*case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}*/
case R.id.settings_button: {
Intent serverIntent = new Intent(getActivity(), SettingsActivity.class);
startActivityForResult(serverIntent, REQUEST_SHOW_SETTINGS);
return true;
}
}
return false;
}
/**
*
* #param data String
* #param append boolean
*/
private void writeToFile(String data, String uploadData, boolean append) {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
String fname2 = "starDust.csv";
File file = new File (myDir, fname);
File file2 = new File (myDir, fname2);
//if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file, append);
out.write(data.getBytes(), 0, data.getBytes().length);
out.flush();
out.close();
FileOutputStream out2 = new FileOutputStream(file2, append);
out2.write(uploadData.getBytes(), 0, uploadData.getBytes().length);
out2.flush();
out2.close();
if(mConnectedDeviceName != null) {
Log.d(TAG, "Connecting " + SP.getString("server_ip", "") + SP.getString("server_username", "") + SP.getString("server_password", ""));
new FTPUploadTask().execute(mConnectedDeviceName, SP.getString("server_ip", ""), SP.getString("server_username", "") , SP.getString("server_password", ""));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
private String readFromFile() {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
File file = new File (myDir, fname);
StringBuilder text = new StringBuilder();
if (file.exists ()) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.insert(0, line + System.getProperty("line.separator"));
}
br.close();
} catch (Exception e) {
}
}
return text.toString();
}
private void readNormal(String readMessage) {
String parsedData[];
if(readMessage.contains(";")) {
if(readMessage.equals(";")) {
parsedData = bufferedMessage.trim().split(",");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.split(";");
bufferedMessage += partialMessage[0];
parsedData = bufferedMessage.trim().split(",");
if (partialMessage.length > 1) {
bufferedMessage = partialMessage[1];
} else {
bufferedMessage = "";
}
}
} else {
bufferedMessage += readMessage.trim();
return;
}
if(parsedData.length == RESPONSE_SIZE && parsedData[0].equals("U")) {
if(parsedData[1].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[1]) > maxU1 || hitTrigger) {
maxU1 = Integer.parseInt(parsedData[1]);
}
}
if(parsedData[2].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[2]) > maxU2 || hitTrigger) {
maxU2 = Integer.parseInt(parsedData[2]);
}
}
if(parsedData[3].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[3]) > maxU3 || hitTrigger) {
maxU3 = Integer.parseInt(parsedData[3]);
}
}
double u1val = Double.parseDouble(parsedData[1]);
double u2val = Double.parseDouble(parsedData[2]);
double u1u2div = 0;
if(u2val > 0) {
u1u2div = ((u1val / u2val) * KFactor);
}
if(parsedData[4].matches("[-+]?\\d*\\.?\\d+")) {
mBatteryPerc.setText(parsedData[4] + "%");
mBattery.setProgress(Integer.parseInt(parsedData[4]));
}
}
taggantType = 0;
if(maxU1 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 4;
} else {
taggantType += 0;
}
if(maxU2 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 2;
} else {
taggantType += 0;
}
if(maxU3 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 1;
} else {
taggantType += 0;
}
Log.d(TAG, Integer.toString(taggantType));
Log.d(TAG, Boolean.toString(hitTrigger));
Log.d(TAG, bufferedMessage);
// Check if hit threshold, if so hitTrigger is enabled.
if(taggantType > 0) {
savedTaggantType = taggantType;
hitTrigger = true;
mPresence.setText("VALID TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#11D901"));
} else if(taggantType == 0 && hitTrigger) {
hitTrigger = false;
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Taggan Type: N" + Integer.toString(savedTaggantType) +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"N" + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
maxU1 = 0;
maxU2 = 0;
maxU3 = 0;
savedTaggantType = 0;
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
/**
* #param readMessage String
*/
public void readIris(String readMessage) {
if(!readoutStarted) {
return;
}
String parsedData[];
if(readMessage.contains(";")) {
readoutStarted = false;
if(readMessage.equals(";")) {
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split(";");
bufferedMessage += partialMessage[0].trim();
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
}
} else {
bufferedMessage += readMessage.trim().replaceAll("\n", "").replaceAll(" +", " ");
return;
}
Log.d(TAG, Arrays.toString(parsedData));
boolean passed = false;
int v1 = 0;
int v2 = 0;
if(parsedData[3].equals("S")) {
passed = true;
String values[] = parsedData[7].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
} else {
Log.d(TAG, Arrays.toString(parsedData));
String values[] = parsedData[5].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"Valid:" + (passed ? "YES" : "NO") +
System.getProperty("line.separator") +
"Values: " + "T" + v1 + " / " + v2 +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"Valid: " + (passed ? "YES" : "NO") + " - " + "T" + v1 + " / " + v2 + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
mListView.setAdapter(arrayAdapter);
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
I have three xml files associated with this problem, but because of space I'll only include the one that contains the ListView and remove the other buttons.
view_list.xml contains the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/viewList"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:id="#+id/listview_holder"
android:layout_alignParentTop="true"
android:layout_alignTop="#id/button_holder"
android:layout_weight=".1"
android:layout_height="wrap_content">
<ListView
android:id="#+id/scanLogView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:maxLines="4096"
android:scrollbars="vertical"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The error was with ArrayAdapter. I changed the decloration from
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, listItems);
It now builds the project and displays the listview.

failed to connect to the ESPoddle server due to IO Exception in my Android Programming

This is my service.java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class TheService extends Service {
private Looper mServiceLooper;
private CommunicationHandler mServiceHandler;
private int mId = 0;
public static final int CONNECT = 67;
public static final int CREATE_MEETING = 3;
public static final int CHECK_OPEN = 4;
public static final int SUBMIT_RESPONSE = 5;
public static final int CHECK_RESPONSES = 6;
public static final int CLOSE_MEETING = 7;
public static final int CHECK_CLOSED = 8;
public void onCreate() {
HandlerThread thread = new HandlerThread("TheServiceWorkerThread",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new CommunicationHandler(mServiceLooper);
Log.d("TheService", "Service Created");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.what = intent.getExtras().getInt("what");
Log.d("TheService", "msg what = " + msg.what);
msg.setData(intent.getBundleExtra("arguments"));
// boolean result=mServiceHandler.sendMessage(msg);
mServiceHandler.sendMessage(msg);
// Log.d("TheService","result = "+result);
return START_STICKY;
}
/*
* onBind has to be defined, it is a hook method in the abstract class
* service. If it is not defined the class remains abstract.
*/
public android.os.IBinder onBind(Intent intent) {
return null;
}
/*
* The rest of the program is the inner class CommunicationHandler
*
* The CommunicationHandler is the Handler for the service. It is
defined as
* an inner class in order to use some of the variables of the Service
* class. The Service method onStartCommand that gets called when an
* Activity starts the service uses the method sendMessage(msg) with a
msg
* built from the data in the intent. The message is received by the
method
* handleMessage. This method uses TCP sockets to communicate via the
* network.
*/
private final class CommunicationHandler extends Handler {
private Scanner in;
private PrintWriter out;
private Socket socket;
private String phone;
private String uid;
public CommunicationHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
Log.d("TheService", "Handle Message Called with msg.what ="
+ msg.what);
switch (msg.what) {
case CONNECT:
connectToServer(msg);
break;
case CREATE_MEETING:
createMeeting(msg);
break;
case CHECK_OPEN:
checkOpen(msg);
break;
case SUBMIT_RESPONSE:
Log.d("TheService", "About to call submitResponse.");
submitResponse(msg);
break;
case CHECK_RESPONSES:
Log.d("TheService", "About to fetch Responses.");
checkResponses(msg);
break;
case CLOSE_MEETING:
Log.d("TheService", "About to close meeting.");
closeMeeting(msg);
break;
case CHECK_CLOSED:
Log.d("TheService", "About to check closed meetings.");
checkClosedMeetings(msg);
break;
default:
// super.handleMessage(msg);
Log.d("TheService", "Returned" + msg.what);
}
}
private void connectToServer(Message msg) {
String serverIP = msg.getData().getString("host");
int port = msg.getData().getInt("port");
phone = msg.getData().getString("phone");
uid = msg.getData().getString("uid");
Log.d("TheService_ConnectToServer", "User ID=" + uid);
boolean isConnected = false;
for (int numberOfAttempts = 0; numberOfAttempts < 3;
numberOfAttempts++) {
try {
// Establish a connection with the server
socket = new Socket();
SocketAddress sockaddr = new
InetSocketAddress(serverIP,
port);
socket.connect(sockaddr, 3000);
//in = new Scanner(new BufferedInputStream(
// socket.getInputStream()));
BufferedReader buf = new BufferedReader(new
InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println(uid);
String connectAck="";
connectAck = buf.readLine();
Log.d("TheService", connectAck);
if (connectAck
.equals(("<Accepted connection from " + uid +
"/>"))) {
sendNotification("Connected!", "Tap me for
actions!",
ActionSelectActivity.class,
ActionSelectActivity.Send_Action, null);
Toast.makeText(getApplicationContext(),
"Connected!",
Toast.LENGTH_SHORT).show();
isConnected = true;
break;
}
} catch (java.net.UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Unknown
host",
Toast.LENGTH_SHORT).show();
Log.d("TheService", "UnKnow Exception");
// stopSelf();
} catch (java.io.IOException e) {
Toast.makeText(getApplicationContext(), "IOException",
Toast.LENGTH_SHORT).show();
Log.d("TheService", "UnKnow Exception");
// stopSelf();
} finally {
if (!isConnected) {
Toast.makeText(
getApplicationContext(),
"Connection Failed on Attemp No. = "
+ (numberOfAttempts + 1),
Toast.LENGTH_SHORT).show();
try {
Thread.sleep(3000); // wait 1 second before
next
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
if (!isConnected) { // 3 attempts and still failed
Toast.makeText(getApplicationContext(),
"Failed to connect! Service will terminate",
Toast.LENGTH_SHORT).show();
}
}
private void createMeeting(Message msg) {
String meetingID = msg.getData().getString("meetingID");
String timeSlot1 = msg.getData().getString("timeSlot1");
String timeSlot2 = msg.getData().getString("timeSlot2");
String timeSlot3 = msg.getData().getString("timeSlot3");
String part1 = msg.getData().getString("part1");
String part2 = msg.getData().getString("part2");
String part3 = msg.getData().getString("part3");
String msgToSend = "<OpenMeeting>" + "<MeetingId " + "\""
+ meetingID + "\"" + "/>" + " <Message text = " + "\""
+ "Please select a time for the coming meeting." +
"\""
+ "/>" + "<time = " + "\"" + timeSlot1 + "\"" + "/>"
+ "<time = " + "\"" + timeSlot2 + "\"" + "/>" + "<time
= "
+ "\"" + timeSlot3 + "\"" + "/>"
+ "<Participant numberOfParticipant =" + "\"" + "3>"
+ "<name = " + "\"" + part1 + "\"" + "/>" + "<name = "
+ "\"" + part2 + "\"" + "/>" + "<name = " + "\"" +
part3
+ "\"" + "/>" + "</Participant>" + "<OpenMeeting/>";
out.println(msgToSend);
String createAck = in.nextLine();
Toast.makeText(getApplicationContext(), createAck,
Toast.LENGTH_SHORT).show();
}
private void checkOpen(Message msg) {
Log.d("TheService", "Check Open Meeting");
String msgToSend = "<CheckOpenMeeting/>";
out.println(msgToSend);
String checkOpenAck = "";
int noOfMeetings=0;
try {
BufferedReader buf = new BufferedReader(new
InputStreamReader(
socket.getInputStream()));
while ( buf.ready()) {
checkOpenAck= buf.readLine();
if (checkOpenAck==null) return;
int iMeetingIDTag = checkOpenAck.indexOf("<MeetingId
");
int i1 = checkOpenAck.indexOf("\"", iMeetingIDTag +
1);
int i2 = checkOpenAck.indexOf("\"", i1 + 1);
String meetingID = checkOpenAck.substring(i1 + 1, i2);
int iSlot1Tag = checkOpenAck.indexOf("<time = ", i2);
int i3 = checkOpenAck.indexOf("\"", iSlot1Tag + 1);
int i4 = checkOpenAck.indexOf("\"", i3 + 1);
String slot1 = checkOpenAck.substring(i3 + 1, i4);
int iSlot2Tag = checkOpenAck.indexOf("<time = ", i4);
int i5 = checkOpenAck.indexOf("\"", iSlot2Tag + 1);
int i6 = checkOpenAck.indexOf("\"", i5 + 1);
String slot2 = checkOpenAck.substring(i5 + 1, i6);
int iSlot3Tag = checkOpenAck.indexOf("<time = ", i6);
int i7 = checkOpenAck.indexOf("\"", iSlot3Tag + 1);
int i8 = checkOpenAck.indexOf("\"", i7 + 1);
String slot3 = checkOpenAck.substring(i7 + 1, i8);
Bundle b = new Bundle();
b.putString("meetingID", meetingID);
b.putString("slot1", slot1);
b.putString("slot2", slot2);
b.putString("slot3", slot3);
sendNotification("You are invited to " + meetingID,
"Tap to respond!", OpenMeetingActivity.class,
OpenMeetingActivity.Respond_Action, b);
noOfMeetings+=1;
Log.d("TheService", checkOpenAck);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (noOfMeetings==0) {
Toast.makeText(getApplicationContext(), "0 Open
meetings, or server not ready. Try Again
Later",Toast.LENGTH_LONG).show();
}
}
private void submitResponse(Message msg) {
Log.d("TheService", "About to submit a response.");
String meetingID = msg.getData().getString("meetingID");
String timeSlot = msg.getData().getString("selectedTimeSlot");
String msgToSend = "<SelectedTime>" + "<MeetingId " + "\""
+ meetingID + "\"" + "/>" + "<time = " + "\"" +
timeSlot
+ "\"" + "/>" + "</SelectedTime>";
Log.d("TheService", "Response = " + msgToSend);
out.println(msgToSend);
String createAck = in.nextLine();
Toast.makeText(getApplicationContext(), createAck,
Toast.LENGTH_SHORT).show();
}
private void checkResponses(Message msg) {
String meetingID = msg.getData().getString("meetingID");
Log.d("The Service", "Fetching Responses for Meeting ID = "
+ meetingID);
String msgToSend = "<CheckMeetingRespond><MeetingId " + "\""
+ meetingID + "\"" + "/><CheckMeetingRespond/>";
out.println(msgToSend);
String checkResponse = "";
Bundle b=new Bundle();
int responseCount=0;
try {
BufferedReader buf = new BufferedReader(new
InputStreamReader(
socket.getInputStream()));
while (buf.ready() ) {
checkResponse=buf.readLine();
int iPartName = checkResponse.indexOf("<name ");
int i1 = checkResponse.indexOf("\"", iPartName + 1);
int i2 = checkResponse.indexOf("\"", i1 + 1);
String partName = checkResponse.substring(i1 + 1, i2);
int iSelectedTime = checkResponse.indexOf("<time = ",
i2);
int i3 = checkResponse.indexOf("\"", iSelectedTime +
1);
int i4 = checkResponse.indexOf("\"", i3 + 1);
String selectedTime = checkResponse.substring(i3 + 1,
i4);
//if (checkResponse==null) return;
if (checkResponse.contains("NumberOfRespond ")) break;
responseCount+=1;
b.putString("Response:"+responseCount+".By:",
partName);
b.putString("Response:"+responseCount+".SelectedTime:", selectedTime);
Log.d("TheService", "Name = "
+ partName + "-> Time = "+selectedTime);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (responseCount==0){
Toast.makeText(getApplicationContext(), "0 Response
avaiable, or server not ready. Try Again
Later",Toast.LENGTH_LONG).show();
return;
}
b.putInt("NoOfReponses", responseCount);
b.putString("MeetingID", meetingID);
sendNotification(responseCount+ " Responses fetched ",
"Tap to close meeting!", CloseMeetingActivity.class,
CloseMeetingActivity.CLOSE_MEETING, b);
}
private void closeMeeting(Message msg) {
Log.d("TheService", "About to close meeting.");
String meetingID = msg.getData().getString("meetingID");
String timeSlot = msg.getData().getString("selectedTimeSlot");
String msgToSend = "<CloseMeeting>" + "<MeetingId " + "\""
+ meetingID + "\"" + "/>" + "<SelectedTime time = " +
"\"" + timeSlot
+ "\"" + "/>" + "</CloseMeeting>";
Log.d("TheService", "Response = " + msgToSend);
out.println(msgToSend);
String createAck = in.nextLine();
Toast.makeText(getApplicationContext(), createAck,
Toast.LENGTH_SHORT).show();
}
private void checkClosedMeetings (Message msg){
Log.d("TheService", "Check Closed Meeting");
String msgToSend = "<CheckClosedMeeting/>";
out.println(msgToSend);
String checkOpenAck = "";
Bundle meetingsIDBundle = new Bundle();
try {
BufferedReader buf = new BufferedReader(new
InputStreamReader(
socket.getInputStream()));
while ( buf.ready()) {
checkOpenAck= buf.readLine();
if (checkOpenAck==null) return;
int iMeetingIDTag = checkOpenAck.indexOf("<MeetingId
");
int i1 = checkOpenAck.indexOf("\"", iMeetingIDTag +
1);
int i2 = checkOpenAck.indexOf("\"", i1 + 1);
String meetingID = checkOpenAck.substring(i1 + 1, i2);
int iSlotTag = checkOpenAck.indexOf("<SelectedTime
time = ", i2);
int i3 = checkOpenAck.indexOf("\"", iSlotTag + 1);
int i4 = checkOpenAck.indexOf("\"", i3 + 1);
String slot = checkOpenAck.substring(i3 + 1, i4);
if (!meetingsIDBundle.containsKey(meetingID)){ //The
bundle is used to avoid duplicate notification of the same meeting
meetingsIDBundle.putString(meetingID, meetingID);
sendNotification("Meeting " + meetingID + " is
closed",
"Selected time is"+slot,
ActionSelectActivity.class,
ActionSelectActivity.Send_Action, null);
}
Log.d("TheService", checkOpenAck);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* This method prepares a notification that calls an Activity.
*/
private void sendNotification(String t, String s, Class target,
String action, Bundle dataBundle) {
// String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.ic_launcher; // icon from resources
mId += 1;
Context context = getApplicationContext(); // application
Context
CharSequence tickerText = "Message from server";
CharSequence contentTitle = t;
CharSequence contentText = s;
NotificationCompat.Builder notification = new
NotificationCompat.Builder(
getApplicationContext()).setSmallIcon(icon)
.setContentTitle(contentTitle).setTicker(tickerText)
.setContentText(contentText).setAutoCancel(true);
/* the notification will call an activity with this intent */
// Intent notifyIntent = new
// Intent(ActionSelectActivity.Send_Action);
Intent notifyIntent = new Intent(action);
// added so that each intent is unique. i.e. to avoid
overwriting
// previous data in"putExtra"
notifyIntent.setData((Uri.parse("custom://"
+ System.currentTimeMillis())));
notifyIntent.setClass(context, target);
notifyIntent.putExtra("arguments", dataBundle);
PendingIntent contentIntent =
PendingIntent.getActivity(context, 0,
notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT
| Notification.FLAG_AUTO_CANCEL);
// notification. |= Notification.FLAG_AUTO_CANCEL;
/* complete configuration and notify */
notification.setContentIntent(contentIntent);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, notification.build());
}
}
}
This is my Main Activity program
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void ConnectClickHandler(View v){
//Toast.makeText(MainActivity.this, "You Just Clicked
Connect!",Toast.LENGTH_LONG).show();
EditText etServerIP = (EditText) findViewById(R.id.ET_ServerIP);
EditText etUID =(EditText) findViewById(R.id.ET_UID);
String ip=etServerIP.getText().toString(); //hold server IP
String uid=etUID.getText().toString(); // hold User ID
//Toast.makeText(MainActivity.this, ip + "
"+uid,Toast.LENGTH_LONG).show();
final Intent intent = new Intent(this, TheService.class);
intent.putExtra("what", TheService.CONNECT);
Bundle b = new Bundle();
b.putInt("port",4444);
b.putString("host",ip);
b.putString("uid", uid);
intent.putExtra("arguments",b);
Log.d("MainActivity","About to start the service");
Toast.makeText( MainActivity.this , "Trying to connect...",
Toast.LENGTH_SHORT).show();
startService(intent);
//Toast.makeText( MainActivity.this , "Connected...",
Toast.LENGTH_SHORT).show();
finish();
}
mainly i want to connect to ESPoodle server using port 4444 but whenever i try to connect it gives me a failed connection which i'm unable to resolve

Can't use the SASLXFacebookPlatformMechanism class in making android xmpp facebook chat client

I m trying to make a simple version facebook messenger.The code that i used has worked well for gtalk and requires facebook authentication to be used for chatting with facebook friends.For that, i have used SASLXFacebookPlatfromMechanism class where i will store the api token and api key along with the apisecret of my app. The problem is SASLXFacebookPlatfromMechanism.java class is full of errors which i cannot resolve at all.Here are my classes-
**MainActivity.java**
public class MainActivity extends ActionBarActivity {
private ArrayList<String> messages = new ArrayList();
private Handler mHandler = new Handler();
private SettingsDialog mDialog;
private EditText mRecipient;
private EditText mSendText;
private ListView mList;
private XMPPConnection connection;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i("XMPPClient", "onCreate called");
setContentView(R.layout.activity_main);
mRecipient = (EditText) this.findViewById(R.id.recipient);
Log.i("XMPPClient", "mRecipient = " + mRecipient);
mSendText = (EditText) this.findViewById(R.id.sendText);
Log.i("XMPPClient", "mSendText = " + mSendText);
mList = (ListView) this.findViewById(R.id.listMessages);
Log.i("XMPPClient", "mList = " + mList);
setListAdapter();
// Dialog for getting the xmpp settings
mDialog = new SettingsDialog(this);
// Set a listener to show the settings dialog
Button setup = (Button) this.findViewById(R.id.setup);
setup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mHandler.post(new Runnable() {
public void run() {
mDialog.show();
}
});
}
});
// Set a listener to send a chat text message
Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try
{
String to = mRecipient.getText().toString();
String text = mSendText.getText().toString();
Log.i("XMPPClient", "Sending text [" + text + "] to [" + to + "]");
Message msg = new Message(to, Message.Type.chat);
msg.setBody(text);
connection.sendPacket(msg);
messages.add(connection.getUser() + ":");
messages.add(text);
setListAdapter();
}catch(Exception e)
{
Toast.makeText(MainActivity.this, "Error="+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Called by Settings dialog when a connection is establised with the XMPP server
*
* #param connection
*/
public void setConnection (XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
}
});
}
}
}, filter);
}
}
private void setListAdapter
() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.multi_line_list_item,
messages);
mList.setAdapter(adapter);
}
}
SettingsDialog.java
public class SettingsDialog extends Dialog implements android.view.View.OnClickListener {
private MainActivity xmppClient;
public SettingsDialog(MainActivity xmppClient) {
super(xmppClient);
this.xmppClient = xmppClient;
}
protected void onStart() {
super.onStart();
setContentView(R.layout.settings);
getWindow().setFlags(4, 4);
setTitle("XMPP Settings");
Button ok = (Button) findViewById(R.id.ok);
ok.setOnClickListener(this);
}
public void onClick(View v) {
final String host = "chat.facebook.com";
final String port = ""+5222;
final String service = "chat.facebook.com";
final String username = "*****";
final String password = "****";
new Thread() {
public void run() {
// Create a connection
ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(port), service);
connConfig.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
} catch (Exception ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
try {
connection.login(username, password);
Log.i("XMPPClient", "Logged in as " + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
xmppClient.setConnection(connection);
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
}
}.start();
dismiss();
}
private String getText(int id) {
EditText widget = (EditText) this.findViewById(id);
return widget.getText().toString();
}
}
SASLXFacebookPlatformMechanism.java
public class SASLXFacebookPlatformMechanism extends SASLMechanism
{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String applicationSecret = "";
private String sessionKey = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException
{
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKeyAndSessionKey, String host,
String applicationSecret) throws IOException, XMPPException
{
if (apiKeyAndSessionKey == null || applicationSecret == null)
{
throw new IllegalArgumentException("Invalid parameters");
}
String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
if (keyArray.length < 2)
{
throw new IllegalArgumentException(
"API key or session key is not present");
}
this.apiKey = keyArray[0];
this.applicationSecret = applicationSecret;
this.sessionKey = keyArray[1];
this.authenticationId = sessionKey;
this.password = applicationSecret;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh)
throws IOException, XMPPException
{
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
cbh);
authenticate();
}
#Override
protected String getName()
{
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException
{
byte[] response = null;
if (challenge != null)
{
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String sig =
"api_key=" + apiKey + "call_id=" + callId + "method="
+ method + "nonce=" + nonce + "session_key="
+ sessionKey + "v=" + version + applicationSecret;
try
{
sig = md5(sig);
} catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException(e);
}
String composedResponse =
"api_key=" + URLEncoder.encode(apiKey, "utf-8")
+ "&call_id=" + callId + "&method="
+ URLEncoder.encode(method, "utf-8") + "&nonce="
+ URLEncoder.encode(nonce, "utf-8")
+ "&session_key="
+ URLEncoder.encode(sessionKey, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8") + "&sig="
+ URLEncoder.encode(sig, "utf-8");
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null)
{
authenticationText =
Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query)
{
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params)
{
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
private String md5(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("utf-8"), 0, text.length());
return convertToHex(md.digest());
}
private String convertToHex(byte[] data)
{
StringBuilder buf = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i++)
{
int halfByte = (data[i] >>> 4) & 0xF;
int twoHalfs = 0;
do
{
if (0 <= halfByte && halfByte <= 9)
{
buf.append((char) ('0' + halfByte));
}
else
{
buf.append((char) ('a' + halfByte - 10));
}
halfByte = data[i] & 0xF;
} while (twoHalfs++ < 1);
}
return buf.toString();
}
#Override
protected String getAuthenticationText(String arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
return null;
}
#Override
protected String getChallengeResponse(byte[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
The code shows error stating
"The method send(String) in the type SASLAuthentication is not applicable for arguments(Response).The constructor Response(String) is undefined"
in the line-->"getSASLAuthentication().send(new Response(authenticationText));"
I am also confused on how to use this SASLXFacebookPlatformMechanism.java class in my MainActivity.class.I have been trying to get a sense of how it works but failing.A complete guideline on how to develop a xmpp facebook chat client using asmack library would be appreciated since the internet lacks enough documentation on it.Thanks.
[I have the apikeys and apitokens,so the empty string will not remain empty]

Java Sensor filter correction

I am engaging with android sensor data filtering. At the same time, I am not good at JAVA. It needs to integrate "FixFilter" class with main source code which starts ENS492SenorsActivity. In this approach, I aimed that filtering data which is taken from accelerometer and orientation sensors. acx is the taken data from accelerometer in the X directiona and orx is the taken data from orientation data in the X direction.
public float FixFilter (double acx, float orx)
{
orx = 0.75*(orx) + 0.25*(acx);
return orx;
}
public class Ens492SenorsActivity extends Activity implements SensorListener
{
final String tag = "IBMEyes";
SensorManager sm = null;
TextView xViewA = null;
TextView yViewA = null;
TextView zViewA = null;
TextView xViewO = null;
TextView yViewO = null;
TextView zViewO = null;
//for gps
TextView xView1 = null;
TextView yView1 = null;
TextView zView1 = null;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Timer mTimer = new Timer();
private int REFRESH_TIME = 1000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
xViewA = (TextView) findViewById(R.id.xbox);
yViewA = (TextView) findViewById(R.id.ybox);
zViewA = (TextView) findViewById(R.id.zbox);
xViewO = (TextView) findViewById(R.id.xboxo);
yViewO = (TextView) findViewById(R.id.yboxo);
zViewO = (TextView) findViewById(R.id.zboxo);
xView1 = (TextView) findViewById(R.id.xbox1);
yView1 = (TextView) findViewById(R.id.ybox1);
zView1 = (TextView) findViewById(R.id.zbox1);
locManager = (LocationManager) getSystemService(this.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
init_arr();
}
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void ShowMap(View v)
{
String uri = String.format("geo:%f,%f", alig.getLatitude(), alig.getLongitude());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
this.startActivity(intent);
}
public double DoruksKalman (double v1, double v2, double v3,double v4,double v5,double v6,double v7,double v8,double v9,double v10 )
{
double result = 0;
//result = 10 / ( 1/ v1 + 1/ v2 +1/ v3 +1/ v4 +1/ v5 +1/ v6 +1/ v7 +1/ v8 +1/ v9 +1/ v10);
result = (v1 + v2 + v3 + v4 +v5 + v6 +v7 + v8 +v9 + v10)/10;
return result;
}
public float FixFilter (double acx, float orx)
{
orx = 0.75*(orx) + 0.25*(acx);
return orx;
}
public void SendToServer(View v)
{
Log.i(getClass().getSimpleName(), "send task - start");
try{
connect("http://192.168.1.117/ens4912/process.php?ip=&lat=" +
DoruksKalman(
alig.getLatitude(), alig.getLatitude(),alig.getLatitude(),
alig.getLatitude(),alig.getLatitude(),alig.getLatitude(),
alig.getLatitude(),alig.getLatitude(),alig.getLatitude(),
alig.getLatitude())+
"&lng="+
DoruksKalman(alig.getLongitude(), alig.getLongitude(),alig.getLongitude(), alig.getLongitude(),
alig.getLongitude(), alig.getLongitude(), alig.getLongitude(),
alig.getLongitude(), alig.getLongitude(), alig.getLongitude())+
"&alt="+
DoruksKalman(alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),
alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),
alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),alig.getAltitude())+
"&accel="+
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9])+
"&mag="+
DoruksKalman(orx_arr[0], orx_arr[1], orx_arr[2], orx_arr[3],
orx_arr[4],orx_arr[5],orx_arr[6],
orx_arr[7],orx_arr[8],orx_arr[9])
);//"http://www.google.com");
}
catch (Exception e)
{
double zero =0.0;
e.printStackTrace();
connect("http://192.168.1.117/ens4912/process.php?ip=&lat=" +
zero+
"&lng="+
zero+
"&alt="+
zero+
"&accel="+
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9])+
"&mag="+
DoruksKalman(orx_arr[0], orx_arr[1], orx_arr[2], orx_arr[3],
orx_arr[4],orx_arr[5],orx_arr[6],
orx_arr[7],orx_arr[8],orx_arr[9])
);
}
Log.i(getClass().getSimpleName(), "send task - end");
}
float orx;
float ory;
float orz;
float acx;
float acy;
float acz;
float [] acx_arr = new float[10];
float [] acy_arr = new float[10];
float [] acz_arr = new float[10];
float [] orx_arr = new float[10];
float [] ory_arr = new float[10];
float [] orz_arr = new float[10];
private void init_arr()
{
for(int i = 0;i <10;i++)
{
acx_arr[i] = 1.0f;
acy_arr[i] = 1.0f;
acz_arr[i] = 1.0f;
orx_arr[i] = 1.0f;
ory_arr[i] = 1.0f;
orz_arr[i] = 1.0f;
}
}
int sensorReadCount = 0;
private final float NOISE = (float) 2.0;
private float mLastX, mLastY, mLastZ;
private boolean mInitialized = false;
public void onSensorChanged(int sensor, float[] values) {
Boolean writeIt = false;
synchronized (this) {
//Log.d(tag, "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);
if (sensor == SensorManager.SENSOR_ORIENTATION) {
xViewO.setText("Orientation X: " +
DoruksKalman(orx_arr[0], orx_arr[1],orx_arr[2],orx_arr[3],orx_arr[4],
orx_arr[5],orx_arr[6],orx_arr[7],
orx_arr[8],orx_arr[9]));
yViewO.setText("Orientation Y: " +
DoruksKalman(ory_arr[0], ory_arr[1],ory_arr[2],ory_arr[3],ory_arr[4],
ory_arr[5],ory_arr[6],ory_arr[7],
ory_arr[8],ory_arr[9]));
zViewO.setText("Orientation Z: " +
DoruksKalman(orz_arr[0], orz_arr[1],orz_arr[2],orz_arr[3],orz_arr[4],
orz_arr[5],orz_arr[6],orz_arr[7],
orx_arr[8],orx_arr[9]));
orx = values[0];
ory = values[1];
orz = values[2];
orx_arr[sensorReadCount%10] = orx;
ory_arr[sensorReadCount%10] = ory;
orz_arr[sensorReadCount%10] = orz;
}
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
acx = values[0];
acy = values[1];
acz = values[2];
if (!mInitialized) {
mLastX = acx;
mLastY = acy;
mLastZ = acz;
mInitialized = true;
}
else {
float deltaX = Math.abs(mLastX - acx);
float deltaY = Math.abs(mLastY - acy);
float deltaZ = Math.abs(mLastZ - acz);
if (deltaX < NOISE) deltaX = (float)0.0;
if (deltaY < NOISE) deltaY = (float)0.0;
if (deltaZ < NOISE) deltaZ = (float)0.0;
mLastX = acx;
mLastY = acy;
mLastZ = acz;
if (deltaX > deltaY) {
//iv.setImageResource(R.drawable.horizontal);
writeIt = false;
} else if (deltaY > deltaX) {
//iv.setImageResource(R.drawable.vertical);
writeIt = true;
} else {
//iv.setVisibility(View.INVISIBLE);
writeIt = false;
}
}
xViewA.setText("Accel X: " + acx);
yViewA.setText("Accel Y: " + acy);
zViewA.setText("Accel Z: " + acz);
/*
xViewA.setText("Accel X: " +
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9]));
yViewA.setText("Accel Y: " +
DoruksKalman(acy_arr[0], acy_arr[1],acy_arr[2],acy_arr[3],acy_arr[4],
acy_arr[5],acy_arr[6],acy_arr[7],
acy_arr[8],acy_arr[9]));
zViewA.setText("Accel Z: " +
DoruksKalman(acz_arr[0], acz_arr[1],acz_arr[2],acz_arr[3],acz_arr[4],
acz_arr[5],acz_arr[6],acz_arr[7],
acz_arr[8],acz_arr[9]));
*/
acx_arr[sensorReadCount%10] = acx;
acy_arr[sensorReadCount%10] = acy;
acz_arr[sensorReadCount%10] = acz;
}
}
try
{
if(sensorReadCount % 10 == 0 && writeIt)// sensorReadCount <= 60 * 10 /* write for 10 minutes*/ )
{
WriteToTXT();
}
}
catch(Exception e)
{
e.printStackTrace();
}
sensorReadCount++;
}
public Boolean IsItBumb()
{
return true;
}
public void onAccuracyChanged(int sensor, int accuracy) {
Log.d(tag,"onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
}
int id = 0;
private void WriteToTXT()
{
id++;
// TO DO
// Buray\FD dolduracaks\FDn\FDz
//sat\FDr sat\FDr
//id - lat - lon -alt - magx - magy - magz - accx - accy -accz - time
double lat;
double lon;
double alt;
double speed;
try
{
lat = alig.getLatitude();
lon = alig.getLongitude();
alt = alig.getAltitude();
speed = alig.getSpeed();
}
catch( Exception e)
{
lat = 0.0;
lon = 0.0;
alt = 0.0;
speed = 0.0;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
String fileName = "doruks_txt";
/*
String sBody = id + " " + lat + " " + lon + " " + alt + " " + orx + " " + ory + " " +
orz + " " + acx + " " + acy + " " + acz + " " + speed + " " + currentDateandTime;
*/
String sBody = lat + "|" + lon + "|" + alt + " " + orx + " " + ory + " " +
orz + " " + acx + " " + acy + " " + acz + " " + speed + " " + currentDateandTime + "|" + id;
generateNoteOnSD(fileName, sBody);
appendLog(sBody);
}
public void appendLog(String text)
{
File logFile = new File("sdcard/mylog.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void generateNoteOnSD(String sFileName, String sBody)
{
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
sm.registerListener(this,
SensorManager.SENSOR_ORIENTATION |
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
sm.unregisterListener(this);
super.onStop();
}
public Location alig = null;
class MyLocationListener implements LocationListener {
public Location gLoc = null;
public Location mLoc = null;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
synchronized (this) {
// This needs to stop getting the location data and save the battery power.
//locManager.removeUpdates(locListener);
alig = location;
String longitude = "Longitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
//editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
//progress.setVisibility(View.GONE);
xView1.setText("X: " + longitude);
yView1.setText("Y: " + latitude);
zView1.setText("Z: " + altitiude);
}
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}

How to decode JSON data sent to server by TripTracker?

I am using a PHP MySQL server model. I want to decode the JSON data that is sent to the server by this code. Any help would be appreciated. The app sends current GPS coordinates to inputed server as JSON array object. I would like to decode it to share with other android users. Thanks a lot. This is the Android code.
public class TrackerService extends Service {
private static final String TAG = "TripTracker/Service";
private final String updatesCache = "updates.cache";
public static TrackerService service;
private NotificationManager nm;
private Notification notification;
private static boolean isRunning = false;
private String freqString;
private int freqSeconds;
private String endpoint;
private final int MAX_RING_SIZE = 15;
private LocationListener locationListener;
private AlarmManager alarmManager;
private PendingIntent pendingAlarm;
private static volatile PowerManager.WakeLock wakeLock;
private AsyncTask httpPoster;
ArrayList<LogMessage> mLogRing = new ArrayList<LogMessage>();
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
ArrayList<List> mUpdates = new ArrayList<List>();
final ReentrantReadWriteLock updateLock = new ReentrantReadWriteLock();
final Messenger mMessenger = new Messenger(new IncomingHandler());
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_LOG = 3;
static final int MSG_LOG_RING = 4;
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
#Override
public void onCreate() {
super.onCreate();
TrackerService.service = this;
endpoint = Prefs.getEndpoint(this);
freqSeconds = 0;
freqString = null;
freqString = Prefs.getUpdateFreq(this);
if (freqString != null && !freqString.equals("")) {
try {
Pattern p = Pattern.compile("(\\d+)(m|h|s)");
Matcher m = p.matcher(freqString);
m.find();
freqSeconds = Integer.parseInt(m.group(1));
if (m.group(2).equals("h"))
freqSeconds *= (60 * 60);
else if (m.group(2).equals("m"))
freqSeconds *= 60;
}
catch (Exception e) {
}
}
if (endpoint == null || endpoint.equals("")) {
logText("invalid endpoint, stopping service");
stopSelf();
}
if (freqSeconds < 1) {
logText("invalid frequency (" + freqSeconds + "), stopping " +
"service");
stopSelf();
}
readCache();
showNotification();
isRunning = true;
/* we're not registered yet, so this will just log to our ring buffer,
* but as soon as the client connects we send the log buffer anyway */
logText("service started, requesting location update every " +
freqString);
/* findAndSendLocation() will callback to this */
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
sendLocation(location);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
/* we don't need to be exact in our frequency, try to conserve at least
* a little battery */
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, AlarmBroadcast.class);
pendingAlarm = PendingIntent.getBroadcast(this, 0, i, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), freqSeconds * 1000, pendingAlarm);
}
#Override
public void onDestroy() {
super.onDestroy();
if (httpPoster != null)
httpPoster.cancel(true);
try {
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(locationListener);
}
catch (Exception e) {
}
/* kill persistent notification */
nm.cancelAll();
if (pendingAlarm != null)
alarmManager.cancel(pendingAlarm);
isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
/* must be done inside of updateLock */
public void cacheUpdates() {
OutputStreamWriter cacheStream = null;
try {
FileOutputStream cacheFile = TrackerService.this.openFileOutput(
updatesCache, Activity.MODE_PRIVATE);
cacheStream = new OutputStreamWriter(cacheFile, "UTF-8");
/* would be nice to just serialize mUpdates but it's not
* serializable. create a json array of json objects, each object
* having each key/value pair of one location update. */
JSONArray ja = new JSONArray();
for (int i = 0; i < mUpdates.size(); i++) {
List<NameValuePair> pair = mUpdates.get(i);
JSONObject jo = new JSONObject();
for (int j = 0; j < pair.size(); j++) {
try {
jo.put(((NameValuePair)pair.get(j)).getName(),
pair.get(j).getValue());
}
catch (JSONException e) {
}
}
ja.put(jo);
}
cacheStream.write(ja.toString());
cacheFile.getFD().sync();
}
catch (IOException e) {
Log.w(TAG, e);
}
finally {
if (cacheStream != null) {
try {
cacheStream.close();
}
catch (IOException e) {
}
}
}
}
/* read json cache into mUpdates */
public void readCache() {
updateLock.writeLock().lock();
InputStreamReader cacheStream = null;
try {
FileInputStream cacheFile = TrackerService.this.openFileInput(
updatesCache);
StringBuffer buf = new StringBuffer("");
byte[] bbuf = new byte[1024];
int len;
while ((len = cacheFile.read(bbuf)) != -1)
buf.append(new String(bbuf));
JSONArray ja = new JSONArray(new String(buf));
mUpdates = new ArrayList<List>();
for (int j = 0; j < ja.length(); j++) {
JSONObject jo = ja.getJSONObject(j);
List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
Iterator<String> i = jo.keys();
while (i.hasNext()) {
String k = (String)i.next();
String v = jo.getString(k);
nvp.add(new BasicNameValuePair(k, v));
}
mUpdates.add(nvp);
}
if (mUpdates.size() > 0)
logText("read " + mUpdates.size() + " update" +
(mUpdates.size() == 1 ? "" : "s") + " from cache");
}
catch (JSONException e) {
}
catch (FileNotFoundException e) {
}
catch (IOException e) {
Log.w(TAG, e);
}
finally {
if (cacheStream != null) {
try {
cacheStream.close();
}
catch (IOException e) {
}
}
}
updateLock.writeLock().unlock();
}
/* called within wake lock from broadcast receiver, but assert that we have
* it so we can keep it longer when we return (since the location request
* uses a callback) and then free it when we're done running through the
* queue */
public void findAndSendLocation() {
if (wakeLock == null) {
PowerManager pm = (PowerManager)this.getSystemService(
Context.POWER_SERVICE);
/* we don't need the screen on */
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"triptracker");
wakeLock.setReferenceCounted(true);
}
if (!wakeLock.isHeld())
wakeLock.acquire();
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
locationListener, null);
}
public static boolean isRunning() {
return isRunning;
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.icon,
"Trip Tracker Started", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Trip Tracker",
"Sending location every " + freqString, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT;
nm.notify(1, notification);
}
private void updateNotification(String text) {
if (nm != null) {
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Trip Tracker", text,
contentIntent);
notification.when = System.currentTimeMillis();
nm.notify(1, notification);
}
}
public void logText(String log) {
LogMessage lm = new LogMessage(new Date(), log);
mLogRing.add(lm);
if (mLogRing.size() > MAX_RING_SIZE)
mLogRing.remove(0);
updateNotification(log);
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
Bundle b = new Bundle();
b.putString("log", log);
Message msg = Message.obtain(null, MSG_LOG);
msg.setData(b);
mClients.get(i).send(msg);
}
catch (RemoteException e) {
/* client is dead, how did this happen */
mClients.remove(i);
}
}
}
/* flatten an array of NameValuePairs into an array of
* locations[0]latitude, locations[1]latitude, etc. */
public List<NameValuePair> getUpdatesAsArray() {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
for (int i = 0; i < mUpdates.size(); i++) {
List<NameValuePair> pair = mUpdates.get(i);
for (int j = 0; j < pair.size(); j++)
pairs.add(new BasicNameValuePair("locations[" + i + "][" +
((NameValuePair)pair.get(j)).getName() + "]",
pair.get(j).getValue()));
}
return pairs;
}
public int getUpdatesSize() {
return mUpdates.size();
}
public void removeUpdate(int i) {
mUpdates.remove(i);
}
private void sendLocation(Location location) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
pairs.add(new BasicNameValuePair("time",
String.valueOf(location.getTime())));
pairs.add(new BasicNameValuePair("latitude",
String.valueOf(location.getLatitude())));
pairs.add(new BasicNameValuePair("longitude",
String.valueOf(location.getLongitude())));
pairs.add(new BasicNameValuePair("speed",
String.valueOf(location.getSpeed())));
/* push these pairs onto the queue, and only run the poster if another
* one isn't running already (if it is, it will keep running through
* the queue until it's empty) */
updateLock.writeLock().lock();
mUpdates.add(pairs);
int size = service.getUpdatesSize();
cacheUpdates();
updateLock.writeLock().unlock();
logText("location " +
(new DecimalFormat("#.######").format(location.getLatitude())) +
", " +
(new DecimalFormat("#.######").format(location.getLongitude())) +
(size <= 1 ? "" : " (" + size + " queued)"));
if (httpPoster == null ||
httpPoster.getStatus() == AsyncTask.Status.FINISHED)
(httpPoster = new HttpPoster()).execute();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
/* respond with our log ring to show what we've been up to */
try {
Message replyMsg = Message.obtain(null, MSG_LOG_RING);
replyMsg.obj = mLogRing;
msg.replyTo.send(replyMsg);
}
catch (RemoteException e) {
}
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
default:
super.handleMessage(msg);
}
}
}
/* Void as first arg causes a crash, no idea why
E/AndroidRuntime(17157): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Void[]
*/
class HttpPoster extends AsyncTask<Object, Void, Boolean> {
#Override
protected Boolean doInBackground(Object... o) {
TrackerService service = TrackerService.service;
int retried = 0;
int max_retries = 4;
while (true) {
if (isCancelled())
return false;
boolean failed = false;
updateLock.writeLock().lock();
List<NameValuePair> pairs = service.getUpdatesAsArray();
int pairSize = service.getUpdatesSize();
updateLock.writeLock().unlock();
AndroidHttpClient httpClient =
AndroidHttpClient.newInstance("TripTracker");
try {
HttpPost post = new HttpPost(endpoint);
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse resp = httpClient.execute(post);
int httpStatus = resp.getStatusLine().getStatusCode();
if (httpStatus == 200) {
/* all good, we can remove everything we've sent from
* the queue (but not just clear it, in case another
* one jumped onto the end while we were here) */
updateLock.writeLock().lock();
for (int i = pairSize - 1; i >= 0; i--)
service.removeUpdate(i);
updateLock.writeLock().unlock();
}
else {
logText("POST failed to " + endpoint + ": got " +
httpStatus + " status");
failed = true;
}
}
catch (Exception e) {
logText("POST failed to " + endpoint + ": " + e);
Log.w(TAG, e);
failed = true;
}
finally {
if (httpClient != null)
httpClient.close();
}
if (failed) {
/* if our initial request failed, snooze for a bit and try
* again, the server might not be reachable */
SystemClock.sleep(15 * 1000);
if (++retried > max_retries) {
/* give up since we're holding the wake lock open for
* too long. we'll get it next time, champ. */
logText("too many failures, retrying later (queue " +
"size " + service.getUpdatesSize() + ")");
break;
}
}
else
retried = 0;
int q = 0;
updateLock.writeLock().lock();
q = service.getUpdatesSize();
cacheUpdates();
updateLock.writeLock().unlock();
if (q == 0)
break;
/* otherwise, run through the rest of the queue */
}
return false;
}
protected void onPostExecute(Boolean b) {
if (wakeLock != null && wakeLock.isHeld())
wakeLock.release();
}
}
}
You can decode the data using json_decode()
<?php
$json = ""; // JSON data
$json_obj = json_decode($json); // As Object
$json_arr = json_decide($json,true) // As Array
var_dump($json_obj);
print_r($json_arr);
// Store Array to database using serialize function
$data = serialize($json_array); // Array will be converted into string
?>

Categories

Resources