My Android application is crashing if it is not connected to wifi - android

package com.example.intracollegeapp;// package name
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import LibPack.UserInfoLib;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class LoginForm extends Activity {
Button login;
TextView username;
TextView password;
UserInfoLib ui;
long msgLength;
long bitLength;
char msg[];
long requiredBits;
long requiredBytes;
int toPad[];
private static final String NAMESPACE = "link to server package on which webservices are stored";
private static final String URL = "link to wsdl file stored on server";
private static final String SOAP_ACTION = "IntraCollegeWS";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
login=(Button)findViewById(R.id.butLogin);
username=(TextView)findViewById(R.id.editText1);
password=(TextView)findViewById(R.id.editText2);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ui= new UserInfoLib();
ui.userId=username.getText().toString();
ui.password=getSHA1(password.getText().toString());
ui=(UserInfoLib)callService(objectToString(ui), "UserLogin", "userInfo");
//ui=(UserInfoLib)stringToObject(temp);
if(ui.firstName.equals("")){
Toast.makeText(v.getContext(), "Please Verify User Name Or Password", Toast.LENGTH_LONG).show();
finish();
}else{
Toast.makeText(v.getContext(), "Login Successfull", Toast.LENGTH_LONG).show();
System.out.println("NAME :"+ui.firstName);
Intent i = new Intent(v.getContext(), MainForm.class);
i.putExtra("uid", ui);
startActivity(i);
finish();
}
}
});
}
public long leftRotateBy(long l, int times) {
return ((l << times) & 0xFFFFFFFFl) | ((l & 0xFFFFFFFFl) >> (32 - times));
}
public int getByteAt(int at) {
if (at < msgLength) {
return (msg[at]);
} else {
at = at - (int) msgLength;
return toPad[at];
}
}
public void padBits(String pass) {
System.out.println("\n\n\n\n");
msg = pass.toCharArray();
msgLength = msg.length;
bitLength = msgLength * 8;
System.out.println("Msg Bit Length: " + bitLength);
System.out.println("MSg Byte Length: " + msgLength);
System.out.println("Required Minimum Bits: " + (bitLength + 65));
long remainder = (bitLength + 65) % 512;
System.out.println("Mod (Bits): " + remainder);
if (remainder == 0) {
requiredBits = 65;
System.out.println("No Padding Needed.");
} else {
requiredBits = (512 - remainder) + 65;
System.out.println(requiredBits + " Bits Padding Needed.");
}
requiredBytes = requiredBits / 8;
toPad = new int[(int) requiredBytes];
System.out.println("Required Bits: " + requiredBits);
System.out.println("Required Bytes: " + requiredBytes);
// manually append 1 to start of pad bits...
toPad[0] = 0x80;
for (int i = 1; i < requiredBytes - 8; i++) {
toPad[i] = 0;
}
long temp = bitLength;
for (int i = (int) (requiredBytes - 1); i >= (int) (requiredBytes - 8); i--) {
int t = (int) (temp & 0xff);
temp = temp >> 8;
toPad[i] = t;
}
System.out.println("TO PAD: ");
for (int i = 0; i < requiredBytes; i++) {
System.out.print(Integer.toHexString(toPad[i]) + " ");
}
System.out.println();
}
public String getSHA1(String pass) {
int kconst[] = new int[]{
0x5A827999,
0x6ED9EBA1,
0x8F1BBCDC,
0xCA62C1D6};
long h0 = 0x67452301;
long h1 = 0xEFCDAB89;
long h2 = 0x98BADCFE;
long h3 = 0x10325476;
long h4 = 0xC3D2E1F0;
long a, b, c, d, e;
padBits(pass);
long totalLength = msgLength + requiredBytes;
System.out.println("TOTAL LENGTH: " + totalLength);
System.out.println("BLOCKS: " + (totalLength / 8));
long w[] = new long[80];
for (int i = 0; i < (int) totalLength; i += 64) {
for (int j = i, kk = 0; j < (i + 64); j += 4, kk++) {
w[kk] = 0xffffffffl & ((getByteAt(j) << 24) | (getByteAt(j + 1) << 16) | (getByteAt(j + 2) << 8) | (getByteAt(j + 3)));
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
for (int kk = 16; kk < 80; kk++) {
w[kk] = (w[kk - 3] ^ w[kk - 8] ^ w[kk - 14] ^ w[kk - 16]);
w[kk] = leftRotateBy(w[kk], 1);
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
long temp = 0;
for (int t = 0; t < 20; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | ((~b) & d)) + e + w[t] + kconst[0];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 20; t < 40; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[1];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 40; t < 60; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | (b & d) | (c & d)) + e + w[t] + kconst[2];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 60; t < 80; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[3];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
h0 = (h0 + a) & 0xFFFFFFFFl;
h1 = (h1 + b) & 0xFFFFFFFFl;
h2 = (h2 + c) & 0xFFFFFFFFl;
h3 = (h3 + d) & 0xFFFFFFFFl;
h4 = (h4 + e) & 0xFFFFFFFFl;
}
return Long.toHexString(h0) + Long.toHexString(h1) + Long.toHexString(h2) + Long.toHexString(h3) + Long.toHexString(h4);
}
Object callService(String INPUT_DATA, String METHOD_NAME, String PARAMETER_NAME){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
PropertyInfo pi = new PropertyInfo();
pi.setName(PARAMETER_NAME);
pi.setValue(INPUT_DATA);
pi.setType(String.class);
request.addProperty(pi);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsRequestSOAP = (SoapObject)envelope.bodyIn;
String resp = resultsRequestSOAP.getPrimitivePropertyAsString("return");
return stringToObject(resp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Object stringToObject(String inp){
byte b[] = Base64.decode(inp);
Object ret = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInput in = new ObjectInputStream(bis);
ret = (Object) in.readObject();
bis.close();
in.close();
} catch(Exception e) {
System.out.println("NOT DE-SERIALIZABLE: " + e);
}
return ret;
}
String objectToString(Object obj){
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(obj);
b = bos.toByteArray();
} catch(Exception e) {
System.out.println("NOT SERIALIZABLE: " + e);
}
return Base64.encode(b);
}
}
/* i have developed an android application which connects to server for login purpose. For connection i have used ksoap2 library. Intracollege webservice is stored on server. The application works fine when connected to server using wifi. if it is not connected to wifi it displays message "application is crashed" and then application stops working.
I only want to display a simple message "Application is not connected to server" if it is not connected to server using wifi.*/

Try this........
public boolean isNet()
{
boolean status=false;
String line;
try
{
URL url = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
while(( line = reader.readLine()) != null)
{
}
status=true;
}
catch (IOException ex)
{
System.out.println("ex in isNet : "+ex.toString());
if(ex.toString().equals("java.net.UnknownHostException: www.google.com"))
status=false;
}
catch(Exception e)
{
}
return status;
}
if(status==true)
{
//Do your operation
}
else
show("No Internet Connection.");
When status is true do your login process.Otherwise show message "Application is not connected to server".

To check for the internet connection try this out
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}

Check this code, this will help you :
Initialize in the class where you want to check network availability.
OtherUtils otherUtils = new OtherUtils();
if (!otherUtils.isNetworkAvailable(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "No Network Available", Toast.LENGTH_LONG).show();
return;
}
Add below class:
public class OtherUtils{
Context context;
public boolean isNetworkAvailable(Context context) {
this.context = context;
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
// boitealerte(this.getString(R.string.alertNoNetwork),"getSystemService rend null");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
This will surely help you.

Related

When using setOnGroupClickListener method report an error “cannot find symbol”

When using setOnGroupClickListener method report an error “cannot find symbol”,
I try to use setOnGroupClickListener to register sublist click event listener to list control,But an error is reported during compilation
error report:
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:142: error: cannot find symbol
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:143: error: method does not override or implement a method from a supertype
#Override
package com.mtb.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import com.xiaomi.mtb.*;
import com.xiaomi.mtb.activity.*;
import com.xiaomi.mtb.R;
import android.util.Log;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MtbNvAutoCheckList1Activity extends MtbBaseActivity {
private ArrayList<NvAutoCheckDataFather> groups = new ArrayList<>();
private ArrayList<ArrayList<NvAutoCheckDataSon>>children = new ArrayList<>();
private ArrayList<NvAutoCheckDataSon>data=new ArrayList<>();
private HashMap<Integer,Integer>hashMap=new HashMap<>();
private static int mNvEfsDataPrintMaxNum = 20;
private static final String LOG_TAG = "MtbNvAutoCheckMainActivity";
private static final int DATA_TYPE_DECIMALISM = 0;
private static int mHexOrDec = DATA_TYPE_DECIMALISM;
private static final int DATA_TYPE_HEX = 1;
private static final int SIGNED_DATA = 0;
private static final int UNSIGNED_DATA = 1;
private static boolean mTmpLogPrintFlag = false;
private ExpandableListView elvBook;
private NvAutoCheckBookAdapter adapter;
private static HashMap<Integer,byte[]>mNvData=new HashMap<Integer,byte[]>(){
{
put(550,new byte[]{8,(byte)138, 70, 115, 6, 98, 16, 5, 112});
put(74,new byte[]{6});
put(453,new byte[]{1});
}
};
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMtbHookAgent = MtbHookAgent.getHook();
int num=0;
Iterator<Map.Entry<Integer,byte[]>> iterator1=mNvData.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry<Integer,byte[]>entry=iterator1.next();
int key=entry.getKey();
byte[] value=entry.getValue();
ByteBuffer byteBuf=mMtbHookAgent.onHookNvOptSync(0, key, mMtbHookAgent.EVENT_OEMHOOK_XIAOMI_NV_READ);
log("onNvEfsReadHookHdl, mNvId = "+key);
int ret = byteBuf.getInt();
int len = byteBuf.getInt();
log("onNvEfsReadHookHdl" + ", len = " + len);
byte[] bytes = null;
if(len<=0){
log("efs config empty");
}else{
bytes = new byte[len];
byteBuf.get(bytes);
}
String mNvFlagResult="false";
for(int i=0; i < value.length;i++){
if(entry.getValue()[i] != bytes[i]){
log("mNVDATA_"+key+"[" + i + "] not the same");
break;
}
log("mNVDATA_"+key+"[" + i + "] identical");
if(i == (value.length - 1)){
mNvFlagResult = "success";
}
}
groups.add(new NvAutoCheckDataFather(key,mNvFlagResult));
if(mNvFlagResult=="false"){
hashMap.put(num, hashMap.size());
NvAutoCheckDataSon mNvAutoCheckDataSon=new NvAutoCheckDataSon("正确的值是: "+onGetStringByByteGroup(value,value.length),"读出的值为: "+onGetStringByByteGroup(bytes,value.length));
children.add(new ArrayList<NvAutoCheckDataSon>(){
{
add(mNvAutoCheckDataSon);
}
});
}
num++;
}
// 利用布局资源文件设置用户界面
setContentView(R.layout.nv_auto_check_list1_config);
// 通过资源标识获得控件实例
elvBook = findViewById(R.id.elvBook);
// 创建适配器
adapter = new NvAutoCheckBookAdapter(this, groups, children, hashMap);
// 给列表控件设置适配器
elvBook.setAdapter(adapter);
// 给列表控件注册子列表单击事件监听器
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition,long l){
if(!hashMap.containsKey(groupPosition)){
return true;
}else{
return false;
}
}
});
}
private static void log(String msg) {
Log.d(LOG_TAG, "MTB_ " + msg);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint) {
return onGetStringByDateType(val, uFlag, bPrint, mHexOrDec, true);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint, int hexOrDec, boolean fillHexZero) {
if (bPrint) {
tmpLog("onGetStringByDateType, byte, val = " + val + ", uFlag = " + uFlag + ", bPrint = " + bPrint + ", hexOrDec = " + hexOrDec + ", fillHexZero = " + fillHexZero);
}
String strVal = null;
BigDecimal bigVal;
byte lowVal = 0;
if (DATA_TYPE_HEX == hexOrDec) {
strVal = Integer.toHexString(val & 0xff);
if (1 == strVal.length() && fillHexZero) {
strVal = "0" + strVal;
}
if (bPrint) {
tmpLog("HEX, strVal = " + strVal);
}
} else {
strVal = "" + val;
if (UNSIGNED_DATA == uFlag && val < 0) {
lowVal = (byte)(val & 0x7f);
bigVal = BigDecimal.valueOf(lowVal).add(BigDecimal.valueOf(Byte.MAX_VALUE)).add(BigDecimal.valueOf(1));
strVal = bigVal.toString();
if (bPrint) {
tmpLog("val < 0, new strVal = " + strVal);
}
}
}
if (null != strVal) {
strVal = strVal.toUpperCase();
}
return strVal;
}
private String onGetStringByByteGroup(byte[] bytes, int len){
String ret="";
for(int i=0;i<len;i++){
String str1=onGetStringByDateType(bytes[i], UNSIGNED_DATA, false);
ret+=str1;
}
return ret;
}
private static void tmpLog(String msg) {
if (mTmpLogPrintFlag) {
log(msg);
}
}
}

how to print large pictures with Android and USB bulk transfer

When I transfer the bytes greater than 16384 bytes when the data will be lost,
I have tried libusb, but libusb I did not find the right development documentation for reference, I wonder if there is no better way to solve this problem?
Here is the code that I print through the bulktransfer, when the transmitted data is less than 16384, it is working!
//convert pic to ZPL
public class ZPLConveter {
private int blackLimit = 380;
private int total = -1;
private int widthBytes = -1;
private boolean compressHex = false;
private static Map<Integer, String> mapCode = new HashMap<Integer, String>();
{
mapCode.put(1, "G");
mapCode.put(2, "H");
mapCode.put(3, "I");
mapCode.put(4, "J");
mapCode.put(5, "K");
mapCode.put(6, "L");
mapCode.put(7, "M");
mapCode.put(8, "N");
mapCode.put(9, "O");
mapCode.put(10, "P");
mapCode.put(11, "Q");
mapCode.put(12, "R");
mapCode.put(13, "S");
mapCode.put(14, "T");
mapCode.put(15, "U");
mapCode.put(16, "V");
mapCode.put(17, "W");
mapCode.put(18, "X");
mapCode.put(19, "Y");
mapCode.put(20, "g");
mapCode.put(40, "h");
mapCode.put(60, "i");
mapCode.put(80, "j");
mapCode.put(100, "k");
mapCode.put(120, "l");
mapCode.put(140, "m");
mapCode.put(160, "n");
mapCode.put(180, "o");
mapCode.put(200, "p");
mapCode.put(220, "q");
mapCode.put(240, "r");
mapCode.put(260, "s");
mapCode.put(280, "t");
mapCode.put(300, "u");
mapCode.put(320, "v");
mapCode.put(340, "w");
mapCode.put(360, "x");
mapCode.put(380, "y");
mapCode.put(400, "z");
}
public String convertFromImg(Bitmap bitmap) {
String cuerpo = createBody(bitmap);
if(compressHex) {
cuerpo = encodeHexAscii(cuerpo);
}
return headDoc() + cuerpo + footDoc();
}
private String createBody(Bitmap originalImg) {
StringBuffer sb = new StringBuffer();
int width = originalImg.getWidth();
int height = originalImg.getHeight();
int rgb,red,green,blue,index = 0;
char binaryChar[] = {'0','0','0','0','0','0','0','0',};
widthBytes = width / 8;
if(width % 8 > 0) {
widthBytes = (((int)width / 8) + 1);
}else {
widthBytes = width / 8;
}
total = widthBytes * height;
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
rgb = originalImg.getPixel(w,h);
red = Color.red(rgb);
green =Color.green(rgb);
blue = Color.blue(rgb);
char auxChar = '1';
int totalColor = red + green + blue;
if(totalColor > blackLimit) {
auxChar = '0';
}
binaryChar[index] = auxChar;
index++;
if(index == 8 || w == (width - 1)) {
sb.append(fourByteBinary(new String(binaryChar)));
binaryChar = new char[]{'0','0','0','0','0','0','0','0'};
index = 0;
}
}
sb.append("\n");
}
return sb.toString();
}
private String fourByteBinary(String binary){
int decimal = Integer.parseInt(binary,2);
if(decimal > 15) {
return Integer.toString(decimal,16).toUpperCase();
}else {
return "0" + Integer.toString(decimal,16).toUpperCase();
}
}
private String encodeHexAscii(String code) {
int maxLine = widthBytes * 2;
StringBuffer sbCode = new StringBuffer();
StringBuffer sbLine = new StringBuffer();
String perviousLine = "";
int counter = 1;
char aux = code.charAt(0);
boolean firstChar = false;
for (int i = 0; i < code.length(); i++) {
if(firstChar) {
aux = code.charAt(i);
firstChar = false;
continue;
}
if(code.charAt(i) == '\n') {
if(counter >= maxLine && aux == '0') {
sbLine.append(",");
}else if(counter >= maxLine && aux == 'F'){
sbLine.append("!");
}else if (counter>20){
int multi20 = (counter/20)*20;
int resto20 = (counter%20);
sbLine.append(mapCode.get(multi20));
if(resto20!=0){
sbLine.append(mapCode.get(resto20) + aux);
} else {
sbLine.append(aux);
}
} else {
sbLine.append(mapCode.get(counter) + aux);
if(mapCode.get(counter)==null){
}
}
counter = 1;
firstChar = true;
if(sbLine.toString().equals(perviousLine)){
sbCode.append(":");
} else {
sbCode.append(sbLine.toString());
}
perviousLine = sbLine.toString();
sbLine.setLength(0);
}
if(aux == code.charAt(i)) {
counter++;
}else {
if(counter > 20) {
int multi20 = (counter/20)*20;
int resto20 = (counter%20);
sbLine.append(mapCode.get(multi20));
if(resto20!=0){
sbLine.append(mapCode.get(resto20) + aux);
} else {
sbLine.append(aux);
}
}else {
sbLine.append(mapCode.get(counter) + aux);
}
counter = 1;
aux = code.charAt(i);
}
}
return sbCode.toString();
}
private String headDoc(){
String str = "^XA " +
"^FO0,0^GFA,"+ total + ","+ total + "," + widthBytes +", ";
return str;
}
private String footDoc(){
String str = "^FS"+
"^XZ";
return str;
}
public void setCompressHex(boolean compressHex) {
this.compressHex = compressHex;
}
public void setBlacknessLimitPercentage(int percentage){
blackLimit = (percentage * 768 / 100);
}
}
And this is the code that I use for transferring the image
//Transferring data using bulktransfer
private void printTask(final UsbDeviceConnection conn) {
try {
convertPDFToImg();
ZPLConveter zp = new ZPLConveter();
zp.setCompressHex(false);
zp.setBlacknessLimitPercentage(50);
command = zp.convertFromImg(bit);
} catch (IOException e) {
e.printStackTrace();
}
bytes = command.getBytes(StandardCharsets.US_ASCII);
conn.bulkTransfer(pointBulkOut, bytes, bytes.length, 500);
}

validation for empty edit text field is not working

I have two TextView, two EditText and two Buttons. I want to set a DialogBox or Toast when the button is clicked without entering any values in the textview. I have two stings, s and s1. If s and s1 or either s or s1 is not entered in the edittext, I must get a toast. I wrote a code for toast but it's not working fine!
Can you help me with this?
This is my code:
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
AnimationDrawable frameanimation;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender=(Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview=(ImageView)findViewById(R.id.imageanim);
imgview.setBackgroundResource(R.drawable.myanim);
frameanimation=(AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
//code for toast//
//if s nd s1 is empty then execute this else executee the rest//
if((s==" ") && (s1==" "))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
else
{
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0,
n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
Change your validation to this :
if((s.equals("")) && (s1.equals("")))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}
Or you can check like this:
if((s.length() == 0) && (s1.length() == 0))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
Tried your code and validation is working :
import java.io.DataInputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
// getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN
// ,WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender = (Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview = (ImageView) findViewById(R.id.imageanim);
frameanimation = (AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
// code for toast//
// if s nd s1 is empty then execute this else executee the rest//
if ((s.equals("")) || (s1.equals(""))) {
Toast.makeText(getBaseContext(), "cnt b empty",
Toast.LENGTH_SHORT).show();
} else {
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0, n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
}
}
}
Try if (s.isEmpty() || s1.isEmpty()) to check if your strings are empty. == and .equals will not work with string comparison because they are comparing the objects and not solely the contents. To check if two strings are equal, you can use firstString.compareTo(anotherString) == 0.
Trim your edittext value then compare
if((("").equals(s.trim())) && (("").equals(s1.trim())))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}

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