I have a problem with setText( TextView ).
view = EgridView.getChildAt( iterator );
parameter = (TextView) view.findViewById( R.id.gridItemParameter );
if( modbus.readAvailable() > 0 ){
if( !((data = modbus.readData()).equals("")) ){
Log.i("-------------TEST-----------", data); // <-------- wrok
//Toast.makeText(getApplicationContext(), data , Toast.LENGTH_LONG).show(); <----- work
// parameter.setText( "test" ); <----------- work
parameter.setText( data ); // <--------- crash
}
}
Why **parameter.setText( data ); **crashes my app?
More code:
public int readAvailable(){
try{
return inStream.available();
} catch( Exception e ){
return 0;
}
}
public String readData(){
try{
if( isConnected == true && socket.isConnected() && inStream != null ){
int i;
int oneByte;
byte byteArray[] = new byte[ 100 ];
int available = inStream.available();
String data = "";
if( available > 0 ){
inStream.read( byteArray );
for( i = 0; i < available; i++ ){
oneByte = byteArray[ i ] & 0xff;
data = data.concat( Integer.toString( oneByte ) + " " );
}
return data; // <-----
} else {
return "";
}
} else {
errorText = "no communication";
return "";
}
} catch( Exception e ){
errorText = e.getMessage();
return "";
}
}
If in readData() I write return "test"; then work
If in readData() I write return byteArray.toString(); then work
If in readData() I write for( i = 0; i < 10; i++ ){ then work
If in readData() I write for( i = 0; i < 11; i++ ){ then crashes
int available = 13 in this situation.
My problem is illogical for me. Please advice.
Thanks for all answers
You can only modify UI elements, such as the TextView, on the UI Thread.
Check this link out from the android documentation: http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
i guess your FINAL STRING Data
make the data cannot be filled
so your variable Data is still null
and you try to setText (null) , that's why..
try to change Final String Data to String Data = ""
or
if there is a problem with your readData function
try this solution
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(con, "Return Nya = " +sb.toString(), 0).show();
Log.v("TEST" , "Return Nya = " + sb.toString());
is.close();
Related
I'm creating an app to read string values over Bluetooth serial port. My data receiving but in two parts. If I send $F00,A,B,0,M# via bluetooth it only reads $ in first part and F00,A,B,0,M# in next part. I provided my code here. Please do correct me if I'm wrong.
InputStream inputStream=null;
int avilableBytes=0;
public ConnectedThread(BluetoothSocket socket){
InputStream temp=null;
try{
temp=socket.getInputStream();
}catch (IOException e){
e.printStackTrace();
}
inputStream=temp;
}
public void run() {
try{
int bytes;
while (true){
try{
avilableBytes=inputStream.available();
if (avilableBytes>0){
byte[] buffer=new byte[avilableBytes];
bytes=inputStream.read(buffer);
final String readMessage=new String(buffer,0,bytes);
bt_handler.obtainMessage(handlerState,bytes,-1,readMessage).sendToTarget();
Log.d("PRAVEEN",readMessage);
}
}catch (IOException e){
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
Data are like stream bytes and can not be processed immediately when it comes with a few bytes. Data will not come all at once as a single packet. You have to use the other byte[] buffer (MainBuffer) in which you will gradually save incoming byte and move the index in that buffer. Then, from time to time (e.g. in the timer once per second) take data from the main buffer and processed it. By default you must implement some data frame with a separator (eg. Data * data * data * - Many ways to do it good or bad). I dealt with this in .net via Xamarin, but just as an example it may be helpfull :
update example, format
In ConnectedThread :
public override void Run()
{
while (true)
{
try
{
int readBytes = 0;
lock (InternaldataReadLock)
{
readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length);
Array.Copy(InternaldataRead, TempdataRead, readBytes);
}
if (readBytes > 0)
{
lock (dataReadLock)
{
dataRead = new byte[readBytes];
for (int i = 0; i < readBytes; i++)
{
dataRead[i] = TempdataRead[i];
}
}
Bundle dataBundle = new Bundle();
dataBundle.PutByteArray("Data", dataRead);
Message message = btlManager.sourceHandler.ObtainMessage();
message.What = 1;
message.Data = dataBundle;
btlManager.sourceHandler.SendMessage(message);
}
}
catch (System.Exception e)
{
btlManager.btlState = BTLService.BTLState.Nothing;
}
}
}
In BTLHandler :
public override void HandleMessage(Message msg)
{
switch (msg.What)
{
case 1:
{
byte[] data = msg.Data != null ? msg.Data.GetByteArray("Data") : new byte[0];
btlService.BTLReceiveData(data);
}
break;
}
}
public void BTLReceiveData(byte[] data)
{
lock (dataReadLock)
{
for (int i = 0; i < data.Length; i++)
{
dataRead[dataReadWriteCursor] = data[i];
dataReadWriteCursor++;
}
}
}
In Timer :
int tmpWriteCursor = dataReadWriteCursor;
int tmpReadCursor = dataReadReadCursor;
lock (dataReadLock)
{
int newBytes = dataReadWriteCursor - dataReadReadCursor;
for (int i = 0; i < newBytes; i++)
{
dataReadMain[dataReadReadCursor] = dataRead[dataReadReadCursor++];
}
}
bool odradkovani = false;
string tmpRadek = "";
int lastLineIndex = 0;
List<string> list = new List<string>();
for (int i = LastWriteLineIndex; i < tmpWriteCursor; i++)
{
if (dataReadMain[i] >= 32 && dataReadMain[i] <= 255)
{
tmpRadek += (char)dataReadMain[i];
}
else if (dataReadMain[i] == 13) odradkovani = true;
else if (dataReadMain[i] == 10)
{
if (odradkovani)
{
odradkovani = false;
list.Add(Utils.GetFormatedDateTime(DateTime.Now) + " " + tmpRadek);
tmpRadek = "";
lastLineIndex = i + 1;
}
}
else
{
tmpRadek += "?" + dataReadMain[i].ToString() + "?";
}
}
WriteDataToLog(list);
LastWriteLineIndex = lastLineIndex;
I received a crash report, which is about java.lang.StringIndexOutOfBoundsException in ZhuangDictActivity$SearchDicAsyncTask.doInBackground
Here is the ZhuangDictActivity$SearchDicAsyncTask.doInBackground:
private class SearchDicAsyncTask extends AsyncTask<String, Integer, String> {
private byte searchStatus;
#Override
protected String doInBackground(String... params) {
if (params[0].length() > 0) {
word = params[0].trim();
long[] index = null;
FileAccessor in = null;
DictZipInputStream din = null;
try {
char key = GB2Alpha.Char2Alpha(word.charAt(0));
tableName = DatabaseHelper.transTableName(key);
index = databaseHelper.queryTable(tableName, word);
if (index != null) {
in = new FileAccessor(new File(dictFileName), "r");
byte[] bytes = new byte[(int) index[1]];
if (isDZDict) {
din = new DictZipInputStream(in);
DictZipHeader h = din.readHeader();
int idx = (int) index[0] / h.getChunkLength();
int off = (int) index[0] % h.getChunkLength();
long pos = h.getOffsets()[idx];
in.seek(pos);
byte[] b = new byte[off + (int) index[1]];
din.readFully(b);
System.arraycopy(b, off, bytes, 0, (int) index[1]);
} else {
in.seek(index[0]);
in.read(bytes);
}
wordDefinition = new String(bytes, "UTF-8");
} else {
searchStatus = 0;
return null;
}
} catch (FileNotFoundException ffe) {
searchStatus = 1;
return null;
} catch (IOException ex) {
ex.printStackTrace();
searchStatus = 2;
return null;
} finally {
try {
if (din != null)
din.close();
if (in != null)
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return wordDefinition;
}
}
The complete code is available here.
I have limited knowledge in Java and Android development. How should I solve this? I intended to post the complete stack traces but stackoverflow do not allow me to do so because it stated my question has too many code. Anyway, the line which is causing the problem is char key = GB2Alpha.Char2Alpha(word.charAt(0));.
It is possible that your string contains only white spaces. meaning it passed the condition:
if (params[0].length() > 0)
But when you call trim(), these are removed, resulting in an empty stream and an "IndexOutOfBoundsException" exception being thrown when you execute:
word.charAt(0)
EDIT
This is not the reason. After a test, when trim is called on a String with only whitespaces, the String remains unchanged.
How can I ping some web server in Android to test if I've Internet connection?
So I need the method which pings the given site and returns false if I've no Internet and true if I have.
See this method, it's the best way to check for connectivity to a given server:
http://developer.android.com/reference/java/net/InetAddress.html#isReachable(int)
Use these methods to ping the server
public static void inSomeWhere()
{
String pingResult = getPingResult("168.126.63.1");
boolean isNetOk = true;
if (pingResult == null) {
// not reachable!!!!!
isNetOk = false;
}
}
public static String getPingResult(String a) {
String str = "";
String result = "";
BufferedReader reader = null;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
Runtime r = Runtime.getRuntime();
Process process = r.exec("/system/bin/ping -c 3 " + a);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int i;
while ((i = reader.read(buffer)) > 0)
output.append(buffer, 0, i);
str = output.toString();
final String[] b = str.split("---");
final String[] c = b[2].split("rtt");
if (b.length == 0 || c.length == 0)
return null;
if(b.length == 1 || c.length == 1)
return null;
result = b[1].substring(1, b[1].length()) + c[0] + c[1].substring(1, c[1].length());
} catch (IOException e) {
return null;
} catch (Exception e) {
return null;
}
finally
{
if(reader != null)
{
try{reader.close();}catch(IOException ie){}
}
}
return result;
}
I can't understand what is wrong in my code . I am getting error in myAddressUniqueness. don't know why.Before i have tried it with string data type but got the same error. It is saying java.null exception.
ArrayList<String> myAddressUniqueness = null;
String name = "hello";
if (indexBody < 0 || !cursor.moveToFirst())
return;
smsList.clear();
do {
// int cursorPostion = cursor.getPosition();
String address;
String msgStr = cursor.getString(indexBody);
String senderNumber = cursor.getString(indexAddr);
Log.d("Name : ", senderNumber);
// String name = cursor.getString(cursor
// .getColumnIndex(PhoneLookup.DISPLAY_NAME));
// Log.d("Name : ",name);
if (name != null) {
address = name;
} else {
address = senderNumber;
}
Log.d("Address: ", address);
flag = 1;
//Log.e("Number: ", addressUniqueness.length + "");
for (j = 0; j < myAddressUniqueness.size(); j++) {
if (myAddressUniqueness.contains(address)) {
flag = 0;
break;
}
}
if (flag == 1) {
myAddressUniqueness.add(new String(address));
i++;
String str = "Sender: " + address + "\n";
smsList.add(str);
}
// TODO Auto-generated catch block
} while (cursor.moveToNext());
Change your declaration to
ArrayList<String> myAddressUniqueness = new ArrayList<String>();
You have it initialized to null. This will instantiate it then you can add data to it.
You should instantiate myAddressUniqueness by myAddressUniqueness = new ArrayList<String>() before using it.
I have a String that I try to split. The following code works
lsSagor = "some text\n Some more text\n More text~Text again\n Text\n text~Some text ..."
final String[] laList = lsSagor.split("~");
String[] laSaga = laList[0].split("\n");
Gives:
laSaga[0] => some text
laSaga[1] => some more text
laSaga[2] => More text
But if I download the textfile, it fails to split and gives:
laSaga[0] => "some text\n Some more text\n More text"
So it seems the first split works, but not the second.
Here is the code I use to download the file
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
//handle the exception !
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
From the documentation
I don't think you will find your string contains any newline character to split on, you would need to do
while ((line = rd.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
to get that and I'm sure there is an easier way to just read it newlines and all in the first place.
Hi I think the problem is in String.split() function
Old method but work :)
public static String[] splitString(String str, char separator)
{
String[] retVal = null;
int length = str.length();
int size = 1;
int jIndx = 0;
int expressionLength = 0;
while ((jIndx = str.indexOf(separator, jIndx + 1)) != -1)
{
size++;
}
retVal = new String[size];
jIndx = 0;
char[] charArray = str.toCharArray() ;
for (int index = 0; index < length; index++)
{
if (charArray[index] == separator)
{
retVal[jIndx] = str.substring(index - expressionLength, index);
jIndx++;
expressionLength = 0;
}
else
expressionLength++;
if (index + 1 == length)
{
retVal[jIndx] = str.substring(index + 1 - expressionLength, index + 1);
}
}
return retVal;
}
This is the (not so beautiful) solution
lsSagor = "some text# Some more text# More text~Text again\n Text# text~Some text ..."
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
guiLaList is used for layout with "\n" and the other list laList to get the information I wanted.