java.lang.ClassCastException in Handler Message - android

Here are the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.demoapp.device.Dev
at com.example.demoapp.MainActivity$MyHandler.handleMessage(MainActivity.java:177)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5140)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is My Handler Code error occurred here in new DevSetNameThread
class MyHandler extends Handler {
public MyHandler() {
}
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
new DevSetNameThread(((Dev) msg.obj), deviceNickName).start();
}
}
And Here is the code from that send message to handler with put object
static final int CMD_TIMEOUT = 8;
static final int DISPLAY_DEVID = 9;
static final int FIND_DEVID = 3;
static final int FIND_ERROR = 4;
public static final int SCAN_CODE = 1;
static final int START_SUBMIT = 5;
static final int SUBMIT_ERROR = 2;
static final int SUBMIT_START = 0;
static final int SUBMIT_SUCCEED = 1;
public static final String TAG = "MainActivity";
static final int TIME_OUT = 6;
Handler handler;
List<Dev> listDev;
Msg msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
info = "";
type = "";
msg = new Msg();
listDev = new ArrayList();
}
class SubmitThread extends Thread {
SubmitThread() {
}
public void run() {
if (listDev.size() > 0) {
Dev d = (Dev) listDev.get(SUBMIT_START);
listDev.remove(d);
if (d != null) {
MainActivity mainActivity;
int index;
Message message = new Message();
message.what = SUBMIT_ERROR;
Log.v("SubmitThread", "\u5f00\u59cb\u63d0\u4ea4\u6570\u636e start..");
int delay = 50;
int reSendTime = SUBMIT_SUCCEED;
Cfg.isSubmitDev = false;
String strId = d.getId();
if (StrTools.stringToInt(strId.substring(SUBMIT_START, SUBMIT_SUCCEED)) == 0) {
mainActivity = MainActivity.this;
devId = strId.substring(SUBMIT_SUCCEED);
} else {
devId = strId;
}
message.obj = devId;
mainActivity = MainActivity.this;
passwd = d.getPass();
byte[] data = new byte[16];
long val = StrTools.stringToInt(devId);
int i = SUBMIT_START;
int index2 = SUBMIT_START;
while (i < CMD_TIMEOUT) {
index = index2 + SUBMIT_SUCCEED;
data[index2] = (byte) ((int) (val % 256));
val /= 256;
i += SUBMIT_SUCCEED;
index2 = index;
}
byte[] b = new byte[CMD_TIMEOUT];
val = StrTools.stringToInt(passwd);
for (i = SUBMIT_START; i < CMD_TIMEOUT; i += SUBMIT_SUCCEED) {
b[i] = (byte) ((int) (val % 256));
val /= 256;
}
byte[] buff = StrTools.byteToSwapByte(b);
i = SUBMIT_START;
while (i < CMD_TIMEOUT) {
index = index2 + SUBMIT_SUCCEED;
data[index2] = buff[i];
i += SUBMIT_SUCCEED;
index2 = index;
}
msg.setId(Cfg.userId);
msg.setCmdType(MSGCMDTYPE.valueOf(-17));
msg.setCmd(MSGCMD.valueOf((int) TIME_OUT));
msg.setTorken(Cfg.tcpTorken);
msg.setData(data);
msg.setDataLen(data.length);
protocol.MessageEnCode(msg);
Log.i(TAG, " data:" + StrTools.bytesToHexString(data));
Log.i(TAG, "sendData:" + StrTools.bytesToHexString(msg.getSendData()));
Message handlermsg = new Message();
handlermsg.obj = devId;
handlermsg.what = SUBMIT_START;
handler.sendMessage(handlermsg);
do {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
reSendTime--;
if (reSendTime <= 0) {
reSendTime = 10;
socketService.socketSendMessage(msg);
}
if (Cfg.isSubmitDev) {
message.what = SUBMIT_SUCCEED;
message.obj = d;
succedDev = d;
handler.sendMessage(message);
return;
}
delay--;
} while (delay > 0);
message.what = SUBMIT_ERROR;
handler.sendMessage(message);
}
}
}
}
Sorry for inconvenience i can't put whole code.
I tried to casting retrieved object with standard code but it's giving me this error so, how can i retrieve Dev object through handler and use it ?

Related

Unzip Password Protect Zip file is slow, How to make it fast?

I using the following class for UnZip password-protected file but unzipping to too much slow to fast it or any improvement in such class or method. Thanks in advance.
Class for Unzip Password Protect Zip file.
public class ZipDecryptInputStream extends InputStream {
private static final int[] CRC_TABLE = new int[256];
private static final int DECRYPT_HEADER_SIZE = 12;
private static final int[] LFH_SIGNATURE = {0x50, 0x4b, 0x03, 0x04};
static {
for (int i = 0; i < 256; i++) {
int r = i;
for (int j = 0; j < 8; j++) {
if ((r & 1) == 1) {
r = (r >>> 1) ^ 0xedb88320;
} else {
r >>>= 1;
}
}
CRC_TABLE[i] = r;
}
}
private final InputStream delegate;
private final String password;
private final int[] keys = new int[3];
private State state = State.SIGNATURE;
private int skipBytes;
private int compressedSize;
private int value;
private int valuePos;
private int valueInc;
public ZipDecryptInputStream(InputStream stream, String password) {
this.delegate = stream;
this.password = password;
}
#Override
public int read() throws IOException {
int result = delegate.read();
if (skipBytes == 0) {
switch (state) {
case SIGNATURE:
if (result != LFH_SIGNATURE[valuePos]) {
state = State.TAIL;
} else {
valuePos++;
if (valuePos >= LFH_SIGNATURE.length) {
skipBytes = 2;
state = State.FLAGS;
}
}
break;
case FLAGS:
if ((result & 1) == 0) {
throw new IllegalStateException("ZIP not password protected.");
}
if ((result & 64) == 64) {
throw new IllegalStateException("Strong encryption used.");
}
if ((result & 8) == 8) {
throw new IllegalStateException("Unsupported ZIP format.");
}
result -= 1;
compressedSize = 0;
valuePos = 0;
valueInc = DECRYPT_HEADER_SIZE;
state = State.COMPRESSED_SIZE;
skipBytes = 11;
break;
case COMPRESSED_SIZE:
compressedSize += result << (8 * valuePos);
result -= valueInc;
if (result < 0) {
valueInc = 1;
result += 256;
} else {
valueInc = 0;
}
valuePos++;
if (valuePos > 3) {
valuePos = 0;
value = 0;
state = State.FN_LENGTH;
skipBytes = 4;
}
break;
case FN_LENGTH:
case EF_LENGTH:
value += result << 8 * valuePos;
if (valuePos == 1) {
valuePos = 0;
if (state == State.FN_LENGTH) {
state = State.EF_LENGTH;
} else {
state = State.HEADER;
skipBytes = value;
}
} else {
valuePos = 1;
}
break;
case HEADER:
initKeys(password);
for (int i = 0; i < DECRYPT_HEADER_SIZE; i++) {
updateKeys((byte) (result ^ decryptByte()));
result = delegate.read();
}
compressedSize -= DECRYPT_HEADER_SIZE;
state = State.DATA;
// intentionally no break
case DATA:
result = (result ^ decryptByte()) & 0xff;
updateKeys((byte) result);
compressedSize--;
if (compressedSize == 0) {
valuePos = 0;
state = State.SIGNATURE;
}
break;
case TAIL:
// do nothing
}
} else {
skipBytes--;
}
return result;
}
#Override
public void close() throws IOException {
delegate.close();
super.close();
}
private void initKeys(String password) {
keys[0] = 305419896;
keys[1] = 591751049;
keys[2] = 878082192;
for (int i = 0; i < password.length(); i++) {
updateKeys((byte) (password.charAt(i) & 0xff));
}
}
private void updateKeys(byte charAt) {
keys[0] = crc32(keys[0], charAt);
keys[1] += keys[0] & 0xff;
keys[1] = keys[1] * 134775813 + 1;
keys[2] = crc32(keys[2], (byte) (keys[1] >> 24));
}
private byte decryptByte() {
int temp = keys[2] | 2;
return (byte) ((temp * (temp ^ 1)) >>> 8);
}
private int crc32(int oldCrc, byte charAt) {
return ((oldCrc >>> 8) ^ CRC_TABLE[(oldCrc ^ charAt) & 0xff]);
}
private enum State {
SIGNATURE, FLAGS, COMPRESSED_SIZE, FN_LENGTH, EF_LENGTH, HEADER, DATA, TAIL
}
}
Usage
InputStream zin = new FileInputStream(new File(zipFilePath));
ZipDecryptInputStream inputStream = new ZipDecryptInputStream(zin, "myPassWord");
ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry ze ;
while ((ze = zis.getNextEntry()) != null) {
FileOutputStream fos = new FileOutputStream(unzipAtLocation + File.separator + ze.getName());
int BUFFER = 2048;
byte[] data = new byte[BUFFER];
int count;
while ((count = zis.read(data, 0, BUFFER)) != -1) {
fos.write(data, 0, count);
}
}
zis.close();
Did you consider using ByteArrayOutputStream instead of FileOutputStream? I have also problem with reading files the other day, which took to much time and I found somewhere in google example with ByteArrayOutputStream and that helps a lot
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] ba = new byte[(int) files[i].length()];
for (int readNum; (readNum = fis.read(ba)) != -1; ) {
bos.write(ba, 0, readNum);
}

How to randomize images in the buttons in android

I am developing a game program where I want to store images in the buttons. I want to randomize the images shown in the buttons when the users play the game again, but I don't know how to randomize the images.
public class MainActivity extends Activity {
public static final String COME_FROM = "come_from";
private int[] id_mc = new int[16];
private Integer[][] img_mc = new Integer [16][2];
private Button[] myMcs = new Button[16];
private int mc_counter = 0;
private int firstid = 0;
private int secondid = 0;
private Boolean mc_isfirst = false;
private int correctcounter = 0;
private TextView tFeedback;
private MediaPlayer mp;
private Boolean b_snd_inc, b_snd_cor;
Random r = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
initGame();
}
private void initGame() {
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
mc_counter = 0;
firstid = 0;
secondid = 0;
mc_isfirst = false;
correctcounter = 0;
tFeedback = (TextView) findViewById(R.id.mc_feedback);
// setup button listeners
Button startButton = (Button) findViewById(R.id.game_menu);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startMenu();
}
});
Button settingsButton = (Button) findViewById(R.id.game_settings);
settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startPrefs();
}
});
// fill arrays with resources
id_mc[0] = R.id.mc0;
id_mc[1] = R.id.mc1;
id_mc[2] = R.id.mc2;
id_mc[3] = R.id.mc3;
id_mc[4] = R.id.mc4;
id_mc[5] = R.id.mc5;
id_mc[6] = R.id.mc6;
id_mc[7] = R.id.mc7;
id_mc[8] = R.id.mc8;
id_mc[9] = R.id.mc9;
id_mc[10] = R.id.mc10;
id_mc[11] = R.id.mc11;
id_mc[12] = R.id.mc12;
id_mc[13] = R.id.mc13;
id_mc[14] = R.id.mc14;
id_mc[15] = R.id.mc15;
img_mc[0][0] = R.drawable.back1;
img_mc[0][1] = R.drawable.ic_img1;
img_mc[1][0] = R.drawable.back2;
img_mc[1][1] = R.drawable.ic_img2;
img_mc[2][0] = R.drawable.back3;
img_mc[2][1] = R.drawable.ic_img3;
img_mc[3][0] = R.drawable.back4;
img_mc[3][1] = R.drawable.ic_img4;
img_mc[4][0] = R.drawable.back5;
img_mc[4][1] = R.drawable.ic_img5;
img_mc[5][0] = R.drawable.back6;
img_mc[5][1] = R.drawable.ic_img6;
img_mc[6][0] = R.drawable.back7;
img_mc[6][1] = R.drawable.ic_img7;
img_mc[7][0] = R.drawable.back8;
img_mc[7][1] = R.drawable.ic_img8;
img_mc[8][0] = R.drawable.back1;
img_mc[8][1] = R.drawable.ic_img1;
img_mc[9][0] = R.drawable.back2;
img_mc[9][1] = R.drawable.ic_img2;
img_mc[10][0] = R.drawable.back3;
img_mc[10][1] = R.drawable.ic_img3;
img_mc[11][0] = R.drawable.back4;
img_mc[11][1] = R.drawable.ic_img4;
img_mc[12][0] = R.drawable.back5;
img_mc[12][1] = R.drawable.ic_img5;
img_mc[13][0] = R.drawable.back6;
img_mc[13][1] = R.drawable.ic_img6;
img_mc[14][0] = R.drawable.back7;
img_mc[14][1] = R.drawable.ic_img7;
img_mc[15][0] = R.drawable.back8;
img_mc[15][1] = R.drawable.ic_img8;
//Collections.shuffle(Arrays.asList(img_mc));
for (int i = 0; i < 16; i++) {
try{
myMcs[i] = (Button) findViewById(id_mc[i]);
myMcs[i].setBackgroundResource(img_mc[i][0]);
myMcs[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int i = 0;
for (int n = 0; n < 16; n++) {
if (id_mc[n] == view.getId())
i = n;
}
doClickAction(view, i);
}
});
}catch(Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}}
}
private void doClickAction(View v, int i)
{
v.setBackgroundResource(img_mc[i][1]);
mc_isfirst = !mc_isfirst;
// disable all buttons
for (Button b : myMcs) {
b.setEnabled(false);
}
if (mc_isfirst) {
// turning the first card
firstid = i;
// re enable all except this one
for (Button b : myMcs) {
if (b.getId() != firstid) {
b.setEnabled(true);
}
}
} else {
// turning the second card
secondid = i;
doPlayMove();
}
}
private void doPlayMove() {
mc_counter++;
if (img_mc[firstid][1] - img_mc[secondid][1] == 0) {
//correct
if (b_snd_cor) playSound(R.raw.correct);
waiting(200);
myMcs[firstid].setVisibility(View.INVISIBLE);
myMcs[secondid].setVisibility(View.INVISIBLE);
correctcounter++;
} else {
//incorrect
if (b_snd_inc) playSound(R.raw.incorrect);
waiting(400);
}
// reenable and turn cards back
for (Button b : myMcs) {
if (b.getVisibility() != View.INVISIBLE) {
b.setEnabled(true);
b.setBackgroundResource(R.drawable.memory_back);
for (int i = 0; i < 16; i++) {
myMcs[i].setBackgroundResource(img_mc[i][0]);
}
}
}
tFeedback.setText("" + correctcounter + " / " + mc_counter);
if (correctcounter > 7) {
Intent iSc = new Intent(getApplicationContext(), Scoreboard.class);
iSc.putExtra("com.gertrietveld.memorygame.SCORE", mc_counter);
startActivity(iSc);
finish();
}
}
public void playSound(int sound) {
mp = MediaPlayer.create(this, sound);
mp.setVolume((float).5,(float).5);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
public static void waiting(int n) {
long t0, t1;
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ((t1 - t0) < (n));
}
private void startMenu() {
Intent launchMenu = new Intent(this, MenuScreen.class);
launchMenu.putExtra(COME_FROM,"PlayGame");
startActivity(launchMenu);
}
private void startPrefs() {
Intent launchPrefs = new Intent(this, Setting.class);
startActivity(launchPrefs);
}
////////////////////////////////
#Override
protected void onRestart() {
super.onRestart();
//String sender = getIntent().getExtras().getString("SENDER");
//initGame();
Toast.makeText(this, "onRestart-sender is " , Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
}
////////////////////////////////
}
You had the Collections.shuffle() part right, you just need to get the randomized list back into your array:
private Integer[][] img_mc = new Integer [16][2];
...
List<Integer[]> img_mc_list = new ArrayList<Integer[]>();
for (Integer[] img : img_mc) {
img_mc_list.add(img);
}
Collections.shuffle(img_mc_list);
img_mc_list.toArray(img_mc);
Or use this:
private void randomize(Integer[][] array) {
int index;
Integer[] temp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}

After several successful runs, progress dialog suddenly returns null pointer exception

I'm developing an app in which the user inputs his/her voice and the app will calculate its features. so I put a progress dialog to inform the user that the app is calculating its features. At first, the application runs perfectly, then on third run, the progress dialog returns null pointer exception. I don't know how to fix. Here's the logcat:
02-22 20:35:11.776: D/AndroidRuntime(24137): Shutting down VM
02-22 20:35:11.776: W/dalvikvm(24137): threadid=1: thread exiting with uncaught exception (group=0x4186bda0)
02-22 20:35:11.786: E/AndroidRuntime(24137): FATAL EXCEPTION: main
02-22 20:35:11.786: E/AndroidRuntime(24137): Process: com.neu.val.activity, PID: 24137
02-22 20:35:11.786: E/AndroidRuntime(24137): java.lang.NullPointerException
02-22 20:35:11.786: E/AndroidRuntime(24137): at android.app.ProgressDialog.setMessage(ProgressDialog.java:325)
02-22 20:35:11.786: E/AndroidRuntime(24137): at com.neu.val.activity.CreateVoiceSample$MfccTask.onProgressUpdate(CreateVoiceSample.java:341)
02-22 20:35:11.786: E/AndroidRuntime(24137): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:648)
02-22 20:35:11.786: E/AndroidRuntime(24137): at android.os.Handler.dispatchMessage(Handler.java:102)
02-22 20:35:11.786: E/AndroidRuntime(24137): at android.os.Looper.loop(Looper.java:146)
02-22 20:35:11.786: E/AndroidRuntime(24137): at android.app.ActivityThread.main(ActivityThread.java:5653)
02-22 20:35:11.786: E/AndroidRuntime(24137): at java.lang.reflect.Method.invokeNative(Native Method)
02-22 20:35:11.786: E/AndroidRuntime(24137): at java.lang.reflect.Method.invoke(Method.java:515)
02-22 20:35:11.786: E/AndroidRuntime(24137): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
02-22 20:35:11.786: E/AndroidRuntime(24137): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
02-22 20:35:11.786: E/AndroidRuntime(24137): at dalvik.system.NativeStart.main(Native Method)
and here's the class:
public class CreateVoiceSample extends ActionBarActivity {
private Button btSpeak, btCance, btSave;
private WaveRecorder waveRecorder;
private ProgressBar progressBar;
private TextView timerText;
private boolean stopped;
private int MAX_DURATION = 2500, progressTime, seconds;
private Timer timer;
static final String TAG = "VAP";
public String codebookString;
private long userId;
private Uri insertFeatures;
private AppDB appDB = new AppDB(this);
/** The recording output file. */
private static File outputFile = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
"recording.wav");
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recordvoice);
userId = getIntent().getLongExtra(Extras.EXTRA_USER_ID, 1);
initializeVar();
enableButtons(true, false, true);
}
public void initializeVar() {
btSpeak = (Button) findViewById(R.id.bSpeak);
btSave = (Button) findViewById(R.id.bSave);
btCancel = (Button) findViewById(R.id.bCancel);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
timerText = (TextView) findViewById(R.id.textView1);
stopped = true;
progressBar.setMax(MAX_DURATION);
startProgress();
}
public void actionBt(View v) {
if (v.getId() == R.id.bSpeak) {
startRecord();
} else if (v.getId() == R.id.bCancel) {
finish();
} else if (v.getId() == R.id.bSave) {
insertFeature(codebookString);
}
}
private void startRecord() {
// TODO Auto-generated method stub
enableButtons(false, false, false);
seconds = 1000;
progressTime = 0;
progressBar.setProgress(0);
timerText.setText("00:00:00");
if (outputFile.exists())
outputFile.delete();
waveRecorder = new WaveRecorder(8000);
waveRecorder.setOutputFile(outputFile.getAbsolutePath());
stopped = false;
try {
waveRecorder.prepare();
waveRecorder.start();
Toast.makeText(getApplicationContext(), "Recording started ... ",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopRecord() {
stopped = true;
waveRecorder.stop();
waveRecorder.release();
waveRecorder.reset();
timer.cancel();
Toast.makeText(getApplicationContext(), "Recording stopped..", Toast.LENGTH_SHORT).show();
calculateMfccs();
startProgress();
}
public void startProgress() {
enableButtons(true,true,true);
final Handler handler = new Handler();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
try {
progress();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer = new Timer();
timer.schedule(timerTask, 1, 1000);
}
public void enableButtons(boolean startBt, boolean stopBt, boolean saveBt,
boolean cancelBt) {
btSpeak.setEnabled(startBt);
btSave.setEnabled(saveBt);
btCancel.setEnabled(cancelBt);
}
public void progress() {
if (!stopped) // call ui only when the progress is not stopped
{
if (progressTime < MAX_DURATION) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int secondsText = seconds / 1000;
progressTime = progressBar.getProgress() + 1000;
progressBar.setProgress(progressTime);
timerText.setText("00:00:0" + secondsText);
seconds += 1000;
} catch (Exception e) {
}
}
});
} else {
stopRecord();
}
}
}
private void calculateMfccs() {
new MfccTask(this).execute(outputFile.getAbsolutePath());
}
private void insertFeature(String password) {
enableButtons(true,false,true);
long modeId = ((VoiceApplication)getApplication()).getModeId();
ContentValues cv = new ContentValues();
cv.put(Feature.SUBJECT_ID, userId);
cv.put(Feature.MODE_ID, modeId);
cv.put(Feature.REPRESENTATION, password);
insertFeatures = this.getContentResolver().insert(Feature.CONTENT_URI, cv);
appDB.onClose();
finish();
Intent changePassIntent = new Intent(this,MainActivity.class);
changePassIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
this.startActivity(changePassIntent);
}
class MfccTask extends AsyncTask<String, Object, String> {
private ProgressDialog progressDialog;
private final Activity parentActivity;
public MfccTask(Activity parentActivity) {
this.parentActivity = parentActivity;
}
#Override
protected String doInBackground(String... params) {
String filename = params[0];
WavReader wavReader = new WavReader(filename);
Log.i(TAG, "Starting to read from file " + filename);
double[] samples = readSamples(wavReader);
Log.i(TAG, "Starting to calculate MFCC");
double[][] mfcc = calculateMfcc(samples);
FeatureVector pl = createFeatureVector(mfcc);
KMeans kmeans = doClustering(pl);
Codebook cb = createCodebook(kmeans);
Gson gson = new Gson();
String codebookJsonString = gson.toJson(cb, Codebook.class);
Log.i(TAG, codebookJsonString);
return codebookJsonString;
}
private Codebook createCodebook(KMeans kmeans) {
int numberClusters = kmeans.getNumberClusters();
Matrix[] centers = new Matrix[numberClusters];
for (int i = 0; i < numberClusters; i++) {
centers[i] = kmeans.getCluster(i).getCenter();
}
Codebook cb = new Codebook();
cb.setLength(numberClusters);
cb.setCentroids(centers);
return cb;
}
private KMeans doClustering(FeatureVector pl) {
long start;
KMeans kmeans = new KMeans(Constants.CLUSTER_COUNT, pl,
Constants.CLUSTER_MAX_ITERATIONS);
Log.i(TAG, "Prepared k means clustering");
start = System.currentTimeMillis();
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
kmeans.run();
Log.i(TAG,
"Clustering finished, total time = "
+ (System.currentTimeMillis() - start) + "ms");
return kmeans;
}
private FeatureVector createFeatureVector(double[][] mfcc) {
int vectorSize = mfcc[0].length;
int vectorCount = mfcc.length;
Log.i(TAG, "Creating pointlist with dimension=" + vectorSize
+ ", count=" + vectorCount);
FeatureVector pl = new FeatureVector(vectorSize, vectorCount);
for (int i = 0; i < vectorCount; i++) {
pl.add(mfcc[i]);
}
Log.d(TAG, "Added all MFCC vectors to pointlist");
return pl;
}
private short createSample(byte[] buffer) {
short sample = 0;
// hardcoded two bytes here
short b1 = buffer[0];
short b2 = buffer[1];
b2 <<= 8;
sample = (short) (b1 | b2);
return sample;
}
private double[][] calculateMfcc(double[] samples) {
MFCC mfccCalculator = new MFCC(Constants.SAMPLERATE,
Constants.WINDOWSIZE, Constants.COEFFICIENTS, false,
Constants.MINFREQ + 1, Constants.MAXFREQ, Constants.FILTERS);
int hopSize = Constants.WINDOWSIZE / 2;
int mfccCount = (samples.length / hopSize) - 1;
double[][] mfcc = new double[mfccCount][Constants.COEFFICIENTS];
long start = System.currentTimeMillis();
for (int i = 0, pos = 0; pos < samples.length - hopSize; i++, pos += hopSize) {
mfcc[i] = mfccCalculator.processWindow(samples, pos);
if (i % 20 == 0) {
publishProgress("Calculating features...", i, mfccCount);
}
}
publishProgress("Calculating features...", mfccCount, mfccCount);
Log.i(TAG, "Calculated " + mfcc.length + " vectors of MFCCs in "
+ (System.currentTimeMillis() - start) + "ms");
return mfcc;
}
private double[] readSamples(WavReader wavReader) {
int sampleSize = wavReader.getFrameSize();
int sampleCount = wavReader.getPayloadLength() / sampleSize;
int windowCount = (int) Math.floor(sampleCount
/ Constants.WINDOWSIZE);
byte[] buffer = new byte[sampleSize];
double[] samples = new double[windowCount * Constants.WINDOWSIZE];
try {
for (int i = 0; i < samples.length; i++) {
wavReader.read(buffer, 0, sampleSize);
samples[i] = createSample(buffer);
if (i % 1000 == 0) {
publishProgress("Reading samples...", i, samples.length);
}
}
} catch (IOException e) {
Log.e(TAG, "Exception in reading samples", e);
}
return samples;
}
#Override
protected void onPostExecute(String result) {
codebookString = result;
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(parentActivity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("Working...");
progressDialog.setMessage("Working...");
progressDialog.setProgress(0);
progressDialog.setMax(10000);
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
}
#Override
protected void onProgressUpdate(Object... values) {
String msg = (String) values[0];
Integer current = (Integer) values[1];
Integer max = (Integer) values[2];
progressDialog.setMessage(msg);
progressDialog.setProgress(current);
progressDialog.setMax(max);
}
}
}
and here's the line(line 341) where the error occured:
progressDialog.setMessage(msg);
I think the problem is in actionBt where the function startRecord() get called and in the line progressBar.setProgress(0); if the progressBar didn't yet initialized then Error will raise.its not a good way to initialize a global variable several times in different lines.

only the original thread that created a view hierarchy can touch its views. android

public class master extends Activity {
ProgressDialog progressDialog;
EditText tahmini_kelime;
EditText girilen_sayi ;
EditText toplam_harf_sayisi ;
Button tamamdir;
TextView jTextArea1;
Vector vector_all,vect_end,vect,recent_search;
BufferedReader read;
String recent_tahmin_kelime;
boolean bayrak,bayrak2 ;
int column_number ;
InputStreamReader inputreader ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.master);
column_number=0;
bayrak=true;
toplam_harf_sayisi=(EditText)findViewById(R.id.toplam_harf);
tahmini_kelime=(EditText)findViewById(R.id.tahmini_kelime);
girilen_sayi=(EditText)findViewById(R.id.sayi_gir);
tamamdir=(Button)findViewById(R.id.tamamdirrrr);
jTextArea1=(TextView)findViewById(R.id.jte);
bayrak2=true;
recent_search = new Vector();
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
tamamdir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if( bayrak2 )
{
if(Integer.parseInt(toplam_harf_sayisi.getText().toString())>8 || Integer.parseInt(toplam_harf_sayisi.getText().toString())<=1)
{
toplam_harf_sayisi.setText("");
Dialog dl=new Dialog(master.this);
dl.setTitle("hatalı giriş");
dl.setCanceledOnTouchOutside(true);
dl.show();
return;
}
int findwordlength = Integer.parseInt(toplam_harf_sayisi.getText().toString());
int k = 0;
String result = "";
jTextArea1.setText("");
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
String resultword = "";
try {
vect = new Vector();
while (read.ready()) {
result = read.readLine();
if (result.length() == findwordlength) {
vect.addElement(result);
resultword = resultword + result + "\n";
k = k + 1;
}
jTextArea1.setText("");
}
jTextArea1.append(resultword + "\n");
RandomKelime(vector_all,0 );
} catch (IOException ex) {
}
toplam_harf_sayisi.setEnabled(false);
girilen_sayi.setEnabled(true);
bayrak2=false;
}
else
{
progressDialog = ProgressDialog.show(master.this, "Bir Düşüneyim :D", "lütfen bekleyiniz...");
Thread thread = new Thread(new Runnable() {
public void run() {
mainGuessWord(column_number);
handler.sendEmptyMessage(0);
}
});
thread.start();
girilen_sayi.setText("");
}
}
});
}
private void mainGuessWord(int look) {
int result_int = 0;
String randomword = "";
int randomword2 = 0;
randomword = tahmini_kelime.getText().toString();
result_int = Integer.parseInt(girilen_sayi.getText().toString());
if (result_int == 0) {
mevcut_degil(vect, randomword);
} else {
elemeAgaci(vect, randomword, result_int);
}
}
public void elemeAgaci(Vector vect, String elem, int length) {
String word = elem.toString();
Vector cmp_vect;
cmp_vect = new Vector();
vect_end = new Vector();
int count = 0;
int countword = 0; // toplam word sayısı
int each_word_total = 0; // her kelimede bulunan harf sayısı
jTextArea1.setText("");
String compare = "";
for (int i = 0; i < vect.size(); i++) {
each_word_total = 0;
compare = "";
for (int j = 0; j < word.length(); j++) {
if(!compare.contains(""+word.charAt(j)))
{
for (int k = 0; k < vect.get(i).toString().length(); k++) {
if (vect.get(i).toString().charAt(k) == word.charAt(j)) {
each_word_total++;
}
}
compare=""+compare+word.charAt(j);
}
}
System.out.println("" + vect.get(i) + " => " + each_word_total);
if (length == each_word_total) {
cmp_vect.add(vect.get(i));
jTextArea1.append(vect.get(i) + "\n");
countword++;
}
}
vect.clear();
for (int l = 0; l < cmp_vect.size(); l++) {
vect.add(cmp_vect.get(l));
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
} else {
column_number = column_number + 1;
if(vect.size()<10){
RandomKelime_Table(vect);
}else{
RandomKelime(vector_all, column_number);
}
}
}
public void mevcut_degil(Vector vect, String m) {
char control[];
control = m.toCharArray();
boolean flag = false;
int countword = 0;
Vector detect;
detect = new Vector();
jTextArea1.setText("");
for (int k = 0; k < vect.size(); k++) {
flag = false;
for (int s = 0; s < control.length; s++) {
if (vect.get(k).toString().contains("" + control[s])) {
flag = true;
}
}
if (!flag) {
detect.addElement(vect.get(k));
countword = countword + 1;
}
}
vect.clear();
for (int s = 0; s < detect.size(); s++) {
vect.addElement(detect.get(s));
}
for (int a = 0; a < countword; a++) {
jTextArea1.append(vect.get(a).toString() + "\n");
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
}
else {
column_number = column_number + 1;
RandomKelime(vect, column_number);
}
}
public void RandomKelime(Vector vector, int k)
{
String sesli[]={"a","e","ı","i","o","ö","u","ü"};
Random a = new Random();
if (k == 0) {
String passedword = "";
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
while (passedword.length() < 8) {
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
tahmini_kelime.setText(passedword);
recent_tahmin_kelime=passedword;
// jTable1.setValueAt(vector_all.get((int) (Math.random() * vector_all.size())), k, 0);
} else {
recent_search.addElement(recent_tahmin_kelime );
int say = 0;
String design = "";
String guess_words = "";
String as="";
int f=0;
int count=0;
int calculate_all=0;
for (int u = 0; u < recent_search.size(); u++) {
design = recent_search.get(u).toString();
bayrak = false;
as="";
count=0;
for(int s=0;s<sesli.length;s++)
{
if(design.contains(""+sesli[s]) && count==0){
as+=""+sesli[s];
count++;
}
}
guess_words = vector_all.get((int) a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
while (say < design.length()) {
calculate_all=0;
while (guess_words.contains("" + as) && !design.equals(guess_words)) {
say = 0;
calculate_all++;
guess_words = vector_all.get( a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
f=f+1;
System.out.println("Tahmın: " + guess_words + " => " + design);
if(calculate_all>vect.size())
{
break;
}
}
say++;
System.out.println("coutn: " + say);
}
}
if (true) {
tahmini_kelime.setText(guess_words);
}
}
}
public void RandomKelime_Table(Vector vector ) {
String passedword = "";
Random a = new Random();
try {
passedword = vect.get(a.nextInt(vect.size())).toString();
} catch (Exception e) {
Dialog dl=new Dialog(master.this);
dl.setTitle("Hatalı Giriş.Yeniden Başlayın.");
dl.setCanceledOnTouchOutside(true);
dl.show();
yeniden_basla();
}
tahmini_kelime.setText(passedword );
}
public void yeniden_basla()
{
bayrak2=true;
girilen_sayi.setEnabled(false);
toplam_harf_sayisi.setEnabled(true);
toplam_harf_sayisi.setText("");
vect.clear();
vector_all.clear();
vect_end.clear();
recent_search.clear();
jTextArea1.setText("");
recent_tahmin_kelime="";
column_number=0;
bayrak=true;
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
this all of my code.
You don't show where you create your handler (onCreate ? onStart ? somewhere else ?). Is it started from the main thread ? If so, you need to be provide a more complete stack trace so we can understand.
If you're starting it from another thread then that's the issue because it's attempting to change progressDialog and that must be done from the main thread.
PS: if you used an AsyncTask you wouldn't have to scratch your head around this as it's designed to do exactly what you want and be thread safe.
Post comment : use an AsyncThread : add the progress bar in onPreExecute(), change run() to doInBackground() and move the dismiss() to onPostExecute(

Unable to receive values more than 255 on Android device from Arduino

I am developing an application to receive data on an Android device from an Arduino. It displays values only up to 255 when I convert it to integer, but I want those values which are sent by the Arduino board. I have tried converting them to strings but that didn't work either.
How can I solve this problem?
Here's the code running on the Android device:
package pkg.MultipleDataReceiveFromArduinoArray;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import pkg.MultipleDataReceiveFromArduino.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;
public class MultipleDataReceiveFromArduinoActivity extends
Activity implements Runnable {
private TextView txtReceivedBytes;
private TextView txtWaterLitres;
private TextView txtSensor1;
private TextView txtSensor2;
private TextView txtSensor3;
private EditText etCallibrationValue;
private Button btnSetCallibrationValue;
private static final String ACTION_USB_PERMISSION =
"com.google.android.DemoKit.action.USB_PERMISSION";
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
private boolean mPermissionRequestPending;
private UsbAccessory mAccessory;
private ParcelFileDescriptor mFileDescriptor;
private FileInputStream mInputStream;
private FileOutputStream mOutputStream;
int countWaterVol = 0;
private int intCallibrationValue = 270;
private static final int MESSAGE_TEMPERATURE = 1;
private static final int MESSAGE_HUMIDITY = 2;
private static final int MESSAGE_WATERLEVEL = 3;
private static final byte COMMAND_OPEN_DOOR = 0x01;
private static final byte COMMAND_CLOSE_DOOR = 0x02;
protected class TelemetryPacket {
private int value;
public TelemetryPacket(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
private int composeInt(byte hi, byte lo) {
int val = (int) hi & 0xff;
val *= 256;
val += (int) lo & 0xff;
return val;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtReceivedBytes=(TextView)findViewById(R.id.txtReceivedBytes);
txtWaterLitres =(TextView)findViewById(R.id.txtWaterLitres);
txtSensor1 = (TextView) findViewById(R.id.txtSensor1);
txtSensor2 =(TextView)findViewById(R.id.txtSensor2);
txtSensor3 =(TextView)findViewById(R.id.txtSensor3);
etCallibrationValue = (EditText)findViewById(R.id.etCallibrationValue);
btnSetCallibrationValue =
(Button)findViewById(R.id.btnSetCallibrationValue);
setupAccessory();
btnSetCallibrationValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intCallibrationValue =
Integer.parseInt(etCallibrationValue.getText().toString());
Toast.makeText(getApplicationContext(),
"Callibration Value:" + intCallibrationValue,
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
super.onResume();
if (mInputStream != null && mOutputStream != null) {
// streams were not null");
return;
}
// streams were null");
UsbAccessory[] accessories = mUsbManager.getAccessoryList();
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if (mUsbManager.hasPermission(accessory)) {
openAccessory(accessory);
} else {
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
mUsbManager.requestPermission(
accessory, mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {
// null accessory
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
super.onDestroy();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//TelemetryPacket p = (TelemetryPacket) msg.obj;
ValueMsg t = (ValueMsg) msg.obj;
txtReceivedBytes.setText("Received Bytes: "+t.getRet());
if (t.getReading4()==1) {
countWaterVol = countWaterVol+1;
txtWaterLitres.setText("Water Produced in Litres:"+
(countWaterVol+"\n"+"Interrupt Signal"+t.getReading3());
} else {
}
txtSensor1.setText("S 1: "+t.getReading1()+","+
"Reading 2: "+t.getReading2());
txtSensor2.setText("S 3: "+t.getReading3()+","+
"Reading 4: "+t.getReading4());
txtSensor3.setText("S 5: "+t.getReading5()+","+
"Reading 6: "+t.getReading6());
Alets alerts = new Alets();
}
};
private void setupAccessory() {
mUsbManager = UsbManager.getInstance(this);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver, filter);
if (getLastNonConfigurationInstance() != null) {
mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
openAccessory(mAccessory);
}
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Thread thread = new Thread(null, this, "OpenAccessoryTest");
thread.start();
// Accessory opened
} else {
// failed to open accessory
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void run() {
int ret = 0;
//byte[] buffer = new byte[16384];
byte[] buffer = new byte[65536];
int i;
while (true) { // read data
try {
ret = mInputStream.read(buffer);
//ret= ret/3;
} catch (IOException e) {
break;
}
i = 0;
while (i < ret) {
int len = ret - i;
// if (len >= 1) {
int value = (int) buffer[0];
Message m = Message.obtain(mHandler);
m.obj = new ValueMsg('f',value,ret,buffer[1],buffer[2],
buffer[3],buffer[4],buffer[5]);
mHandler.sendMessage(m);
i += 1;
}
}
}
public static final long unsignedIntToLong(byte[] b)
{
long l = 0;
l |= b[0] & 0xFF;
l <<= 8;
l |= b[1] & 0xFF;
l <<= 8;
l |= b[2] & 0xFF;
l <<= 8;
l |= b[3] & 0xFF;
return l;
}
public static int unsignedByteToInt(byte b) {
return (int) b & 0x10;
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
openAccessory(accessory);
} else {
// USB permission denied
}
}
} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (accessory != null && accessory.equals(mAccessory)) {
// accessory detached
closeAccessory();
}
}
}
};
}
And here's the Arduino code (sketch):
#include <Usb.h>
#include <adk.h>
uint8_t b;
USB Usb;
ADK adk(&Usb,
"Ashok Kateshiya", // Manufacturer Name
"analog TEST", // Model Name
"TDS test ", // Description (user-visible string)
"0.1", // Version
"http://www.ashokkateshiya.co.cc",
"123456789"); // Serial Number (optional)
#define tds_pin A15
#define flow_pin 22
#define LLS_pin 49
float avg[10];
float value = 0;
int count;
int pin_state = 0, pin_old_state = 0;
int pulse_counter = 0;
int LLS_state;
int LLS_flag = 0;
int sensor_flag = 0;
int timer_flag = 0;
uint8_t msg[7] = { 0x00 };
uint16_t len = sizeof(msg);
uint8_t rcode;
void setup()
{
Serial.begin(115200);
Serial.print("\r\nADK demo start");
if (Usb.Init() == -1)
{
Serial.print("\r\nOSCOKIRQ failed to assert");
while(1); // halt
}
pinMode(tds_pin, INPUT);
pinMode(flow_pin, INPUT);
pinMode(LLS_pin, INPUT);
digitalWrite(LLS_pin, HIGH);
digitalWrite(flow_pin, HIGH);
TIMSK1 = 0x01;
TCCR1A = 0x00;
TCNT1 = 0x85EF;
TCCR1B = 0x05;
}
void loop()
{
Usb.Task();
if (adk.isReady() == false)
{
return;
}
TDS();
flow();
LLS();
}
void TDS()
{
for (count = 0; count < 10; count++)
{
avg[count] = analogRead(tds_pin);
}
for (count = 0; count < 10; count ++)
{
if (count == 0)
{
value = avg[count];
}
else
{
value = value + avg[count];
}
}
if (len > 0)
{
msg[0] = 0x1;
msg[1] = value/10;
rcode = adk.SndData (6, msg );
Serial.print("TDS 0 : ");
Serial.println(msg[0]);
Serial.print("TDS 1 : ");
Serial.println(msg[1]);
delay(10);
}
if (rcode && rcode != hrNAK)
USBTRACE2("DATA rcv :", rcode);
}
void flow()
{
pin_state = digitalRead(flow_pin);
if (pin_state == LOW)
{
pin_old_state = pin_state;
}
if ((pin_state == HIGH) && (pin_old_state == LOW))
{
pin_old_state = pin_state;
pulse_counter = (pulse_counter + 1);
sensor_flag = 1;
}
if ((pulse_counter / 25 == 1) && (sensor_flag == 1))
{
pulse_counter = 0;
sensor_flag = 0;
msg[2] = 0x2;
msg[3] = 1;
rcode = adk.SndData (6, msg );
Serial.print("value :");
Serial.println(msg[3]);
if (rcode && rcode != hrNAK)
{
USBTRACE2 ("USB DATA : ", rcode);
}
}
else
{
msg[2] = 0x2;
msg[3] = 0;
rcode = adk.SndData (6, msg );
Serial.print("value :");
Serial.println(msg[3]);
if (rcode && rcode != hrNAK)
{
USBTRACE2 ("USB DATA : ", rcode);
}
}
delay(10);
}
void LLS()
{
LLS_state = digitalRead(LLS_pin);
if (LLS_state != 0)
{
if (len > 0)
{
msg[4] = 0x3;
msg[5] = 0x0;
rcode = adk.SndData (6, msg );
Serial.print("LLS 4 : ");
Serial.println(msg[4]);
Serial.print("LLS 5 : ");
Serial.println(msg[5]);
}
}
else
{
msg[4] = 0x3;
msg[5] = 0x1;
rcode = adk.SndData (6, msg );
Serial.print("LLS 0 : ");
Serial.println(msg[4]);
Serial.print("LLS 2 : ");
Serial.println(msg[5]);
}
if (rcode && rcode != hrNAK)
USBTRACE2("DATA rcv :", rcode);
delay(10);
}
/****** timer overflow *******/
ISR(TIMER1_OVF_vect)
{
TCNT1 = 0x85EF;
if (pin_state == pin_old_state )
{
timer_flag = 1;
}
}
It looks like the problem is in the Arduino sketch. The msg array contains (unsigned) bytes which have a maximum value of 255.
The line:
msg[1] = value/10
implicitly truncates value/10 (which is an integer between 0 and 1023 - see http://arduino.cc/en/Reference/analogRead) to a maximum of 255.
To send value/10 you'll need to split it over 2 bytes. For example:
msg[1] = (uint8_t) (i & 0xFF);
msg[2] = (uint8_t) ((i >> 8) & 0xFF);
And msg will have to be one byte longer to accomodate.
On the Android (Java) side you'll need to do something like:
int value = (int) buffer[0];
// ...
int tds = buffer[1] + (buffer[2] << 8);
m.obj = new ValueMsg('f', value, ret, tds,
buffer[3], buffer[4], buffer[5], buffer[6]);
which will require a change to the definition of ValueMsg to accomodate.
Also, there may be a problem with the calls to SndData (assuming the library being used here is the USB_Host_Shield_2.0) as they always send 6 bytes even though in the first time through loop all 6 bytes of msg won't have been initialized.

Categories

Resources