How to ping the server in Android? - android

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;
}

Related

Android SDK AsyncTask doInBackground not running

plz help me
I did added async library at my project and checked already, I don't know why code flow doesn't go in to asynctask
my Update code doesn't execute.
in this line my update calss doesnt run
dataupdate.execute();
CODE:
public class Update extends AsyncTask<Void, Void, Integer> {
private String User;
private final String mLink;
public Update(String user) {
User = user;
mLink = "http://www./Update.php";
}
#Override
protected Integer doInBackground(Void... params) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
}
return null;
}
}
Main:
showProgress(true);
dataupdate = new Update(username);
dataupdate.execute();
// dataupdate.execute((Void) null);
showProgress(false);
do it like this
public class Update extends AsyncTask<String, String, Integer> {
#Override
protected Integer doInBackground(String... params) {
User user=params[0]; //get string user value here
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(user, "UTF8");
URL mylink = new URL(mLink);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
int f = 0, w = 0, C = 0;
String name = null;
String status = null;
Integer money = null;
boolean isDebtor = false;
boolean isCreditor = false;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
if (w == 1) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isDebtor = true;
name = temp2;
}
} else if (w == 2) {
String temp2 = line.substring(f, i);
if (!temp2.equals(User)) {
isCreditor = true;
name = temp2;
}
} else if (w == 3) {
String temp2 = line.substring(f, i);
money = Integer.parseInt(temp2);
} else if (w == 4) {
String temp2 = line.substring(f, i);
status = temp2;
}
f = i + 1;
w++;
}
}
Pair<String, Pair<Integer, String>> temp = new Pair<>(name, new Pair<>(money, status));
if (isDebtor) {
MainActivity.Debtor.add(temp);
}
if (isCreditor) {
MainActivity.Creditor.add(temp);
}
}
} catch (Exception e) {
e.printstacktrace();
}
return null;
}
}
to run
//put username value in execute
new Update()execute(username);

Database insert data

I receive data in webservice and insert in sqlite database Android but if filed is empty repeat before filed As far as new filed no empty and repeat ...
please help me:
public class gfc extends AsyncTask {
private String Link = "";
private String Count = "";
private String tid = "";
private String tim = "";
private String tuser = "";
private String tusername = "";
private String tmatn = "";
private String tcomments = "";
private String tlikes = "";
private String tdate = "";
private String tip_addr = "";
private database db;
public gfc(String link, String count, Context c) {
Link = link;
Count = count;
db = new database(c);
}
#Override
protected String doInBackground(Object... arg0) {
try {
String data = URLEncoder.encode("count", "UTF8") + "=" + URLEncoder.encode(Count, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
db.open();
while ((line = reader.readLine()) != null) {
int f = 0;
int c = 0;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
String temp = line.substring(f, i);
if (c == 0) {
tid = temp;
}
if (c == 1) {
tdate = temp;
}
if (c == 2) {
tuser = temp;
}
if (c == 3) {
tusername = temp;
}
if (c == 4) {
tip_addr = temp;
}
if (c == 5) {
tcomments = temp;
}
if (c == 6) {
tlikes = temp;
}
if (c == 7) {
tim = temp;
}
if (c == 8) {
tmatn = temp.replace("^", "\n");
}
c += 1;
f = i + 1;
}
}
db.insert(tid, tuser, tusername, tmatn, tcomments, tlikes, tdate, tip_addr, tim);
sb.append("t");
}
db.close();
index.res = sb.toString();
} catch (Exception e) {}
return "";
}
}

Solving StringIndexOutOfBoundsException

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.

setText crashes my app - inStream.read

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();

Fail to split downloaded txt file

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.

Categories

Resources