Error with internet connectivity for an android activity - android

Hello Guys,
I am creating an Android App, which uses the net connection to fetch a simple .php page which simply shows the current visitor counter.
According to the standard, I tried to implement net connection and web page fetching on a different thread using asynctask class, however, i am facing some problems.
Here is the code
public void myClickHandler(View view) {
// Gets the URL from the UI's text field.
String stringUrl = urlText.getText().toString();
//String stringUrl = "android.bisoft.in/index.php";
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}
}private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
} }}//Reads an InputStream and converts it to a String. public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {Reader reader = null;reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len];reader.read(buffer);return new String(buffer);}}`
When i run the project, (Using an android device emulator), it does not connect to the internet at all, i.e. It does not even show the "No network connection available". error, it simply shows the textview with the default value.
I tried downloading the bluestacks emulator and running it in there, and the same thing happened, just the textview displays without any webpage being fetched or without showing any signs of internet connection activity.
When I searched the net, i came across the fact that there might be a problem with my device emulator's internet connectivity, I am currently developing and testing on a pc, with a wired broadband connection.
I tried doing this
" In eclipse go to DDMS
under DDMS select Emulator Control ,which contains Telephony Status in telephony status contain data -->select Home , this will enable your internet connection ,if you want disable internet connection for Emulator then --->select None
(Note: This will enable internet connections only if you PC/laptop on which you are running your eclipse have active internet connections.) " - some answerer from stackoverflow
but when i opened the ddms.bat from the tools directory of the sdk, it showed me a warning that this batch file was deprecated, i ignored it, and i navigated to emulator control, but I am not even able to select or interact with anything in that tab and all the buttons and textboxes are greyed out.
Thanks in advance for the assistance.
Edit:
I have used the two necessary permissions for the internet connectivity checking and usage
"<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />"
I have tried to run it in a Samsung Galaxy y duos lite, the App runs but the same problem persists, the phone is not connected to the net, so i assume the "no internet connection" message should be displayed, but instead, it just shows the default value of the text field. Any help is greatly appreciated as I am at a wit's end.

This task can be completed much easier using the droidQuery library:
$.ajax(new AjaxOptions().url(stringUrl)
.type("GET")
.dataType("String")
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
textView.setText((String) params[0]);
}
})
.error(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
textView.setText("Unable to retrieve web page. URL may be invalid.");
}
}));

Did you write the good permissions the manifest ?
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You really should try it on a real phone. Emulators are hard to setup for Internet connection.

Related

Android: way to detect if the user changed system time while the app was stopped

I'm developing an Android application for in-house of a certain company, and it needs to log the working time of employees. Therefore, the work with system time is crucial. My application badly needs to know when the user changes the system time. Big deal, you say, see this: Is there a way to detect when the user has changed the clock time on their device?
The problem is that the user may circumvent that solution by doing Force Stop of the application prior to changing the time. The application then won't receive system notification, which is brilliantly described here: https://stackoverflow.com/a/19856367/1309803
I don't mind checking that upon the next launch of the application, but how can I possibly know if the user has changed the time? I'm aware about SystemClock.elapsedRealtime(). I could figure time shift based on delta of those values provided that the user hasn't reboot the device, but this is what I'm unsure of. My application is subscribed to BOOT_COMPLETED event, but that one won't be received either while the application is in stopped state.
And, to cap it all, employees of that company are supposed to work in condition of having no network access, so I can't rely on Web servers. So is there any other possible approach?
Getting the time from the third-party servers is not reliable most of the times and some of them are paid services.
If you want to get the exact time and check with the phone whether it is correct or not, irrespective of the proper way, you can use the following simple trick to get the actual time.
private class GetActualTime extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result.append(line);
in.close();
}
else {
return "error on fetching";
}
return result.toString();
} catch (MalformedURLException e) {
return "malformed URL";
} catch (IOException e) {
return "io exception";
} finally {
if (urlConnection != null) {urlConnection.disconnect();
}
}
} catch (Exception e) { return "null"; }
}
#Override
protected void onPostExecute(String time) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("h:mm");
String times = mdformat.format(calendar.getTime());
try {
String areatime = time.substring(time.indexOf(String.valueOf(times)), time.indexOf(String.valueOf(times)) + 5).trim();
Toast.makeText(this, "The actual time is " + areatime, Toast.LENGTH_SHORT).show();
}
catch(IndexOutOfBoundsException e){
Toast.makeText(this, "Mobile time is not same as Internet time", Toast.LENGTH_SHORT).show();
}
}
}
}
Call the class in the onCreate();
new GetActualTime().execute("https://www.google.com/search?q=time");
So this is actually getting the time from Google. This works pretty awesomely in my projects. In order to check whether the system time is wrong, you can use this trick. Instead of depending on the time servers, you can trust Google.
As it is more sensitive in checking, even a minute ahead or lag will catch the exception. You can customise the code if you want to handle that.

Android recyclerView HttpURLConnection

I have a recyclerview in wich each row contains an url, and the urls can expire in any moment.
I would like the user to not be forced to click on the url to check if it's not valid but I'd rather change the row's color in that case to notify the user.
This is the method I use to check if the url is still valid:
private boolean isUrlStillValid(String url) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestProperty("Accept-Encoding", "");
int responseCode = con.getResponseCode();
con.disconnect();
return responseCode == HttpURLConnection.HTTP_OK;
}catch(Exception e) {
return false;
}
}
I initially thought of launching an AsyncTask in the onBindViewHolder method of the recycler view where I check the url validity, but this will open a lot of connections simultaneously every time a row is shown and will cause very bad performance and memory issues I think.
Do you have any tip/suggestions on how to achieve this?
Do you have any tip/suggestions on how to achieve this?
for each url create a runnable and run all of them on fix thread pool with ExecutorService.
for example you can have 5 threads at a time with below code:
ExecutorService executor = Executors.newFixedThreadPool(5);
and also I recommend to save the result somewhere so when the user plays with scrollbar it dose not check the url again and again and again ...

Connect To VSFTP using Android

hello I am trying to connect from a android to a vsftp server
the company that hosts the server gave me the username and password and #ip.
I made an example to connect me and download a file, but I have problem to login, the connection is made but after there is no no answer, I use a virtual android device to test my example exemple. the problem is in the method mftp.login it returns false .
this is my class that connect to the server
private class connection extends AsyncTask{
#Override
protected Object doInBackground(Object... params) {
boolean retour = ftpConnect( "x.y.z.w", "username", "password", 21);
return retour;
}
public boolean ftpConnect(String host, String username,String password, int port){
try {
mFTPClient = new FTPClient();
try {
mFTPClient.connect(host, 21);
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
/* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE
* for transferring text, image, and compressed files.
*/
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
boolean status = mFTPClient.login(username, password);
Log.i("cause", "this is the status of loging "+status);
FileOutputStream desFileStream = new FileOutputStream(Environment.getExternalStorageDirectory()+"/doc.pdf");
mFTPClient.retrieveFile("x.y.z.w/mydirectory/doc.pdf", desFileStream);
return status;
}
}catch (Exception e){
Log.e(username,"no idea");
}
} catch(Exception e) {
Log.e(username,"no idea 2 ");
}
return false;
}
i'm sure i don't have eror in my code ,
I tried to connect from a web page, but I can not, I tried with dos command but there's no response, they told me that i can just connect from an android device.
I searched for vsftp and I found that it is secured.
1* my questions is that can i connect from a virtual device?
2* which configuration they did to not allow for the connection from web page or virtual device?
I already tried with filezilla but it gave 530 login incorect
3* could you tell me what causes that do not allow me to login to the server . the problem comes from my program or from the server.
4* i use apache library for connecting to the server ftp , it's too good for vsftp ?
and thank you very much
If you can acces from a web/filezilla and they allow to acces from out of their local network, sure yes.
Dont know but if they dont allow external connections you cant. they probably do it for security.
As you explain, of the server.
I think that yes.
Conclusion: If they do not allow external connections you can't connect for example here is a guy that mount this server and he should enable connections for his own red.
http://ubuntuforums.org/showthread.php?t=2068591

Android app doesn't work on Android 4

I created an Android project on 2.3.3 and tried it on mobile 2.3.3, everything works OK. It didn't work on mobile 4, so I re-built for Android 4, but I have the same problem.
This is the code:
public void FTP_Download(){
String server = "192.168.1.135";
int port = 21;
String user = "pc1";
String pass = "1551";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
Toast.makeText(getBaseContext(), "download starting.",Toast.LENGTH_LONG).show();
// APPROACH #1: using retrieveFile(String, OutputStream)
String remoteFile1 = "i.xml";
File downloadFile1 = new File("sdcard/i.xml");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
Toast.makeText(getBaseContext(), "File #1 has been downloaded successfully.",Toast.LENGTH_LONG).show();
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Note:
I use commons-net-3.1 to connect.
In android version 2.3 above you can not start internet connection from main UI thread. Instead you should use AsyncTask. I assumed you are not using AsyncTask. If you are, then post the code and log cat also. Some examples of other operations that ICS and HoneyComb won't allow you to perform on the UI thread are:( from link posted in comment below ) -
Opening a Socket connection (i.e. new Socket()).
HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
Attempting to connect to a remote MySQL database.
Downloading a file (i.e. Downloader.downloadFile()).
You should not use the main UI Thread to start a network connection or read/write data from it as #phazorRise explained it. But I strongly disagree with using an AsyncTask to perform your download. AsyncTask have been designed for short living operations and downloading a file doesn't belong to that category.
The most relevant way to achieve your goal, if your files are big (and I assume it depends on users, so we can say they are big) is to use a service to download the files.
I invite you to have a look at RoboSpice, it will give your app robustness for networking and it's really the most interesting library for network requests on Android.
Here is an inforgraphics to get familiarized with alternatives and understand why using a service is better than any other technology.
When I use "internet conections" programming for andoid 4, I do an Async Task as follows:
You can put this Class code into the same file as principal file to intercatue with global variables or functions.
public class MyAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String url = urls[0]
try {
//Connection request code, in your case ftp
} catch (Exception e) {
//Catch code
}
}
#Override
protected void onPostExecute(String result) {
//Code to de After the connection is done
}
}
Then, in the Activity I call the Asyn Task
String url = "http://...";
new MyAsyncTask().execute(url);
Edit
Here it's explained how to use Async Task, with an example
http://developer.android.com/reference/android/os/AsyncTask.html
I added this code, and all thing OK
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Note: I taked the code from #user1169115 comment in another post.
This isn't the best soluation, but I don't know why asynctask isn't work, so I don't have another choice.

Android HttpURLConnection VERY slow

This is the situation I'm facing with the code below:
As you can see I'm trying to read an HTTP stream. When I run the following code on the Android simulator it works 100% of the time, when I run the following code on my Galaxy S3 while on 3G it works 100% of the time, when I try to connect to the URL using my laptop browser it works 100% of the time, when I try to connect using the Galaxy S3 browser (in both wifi and 3g) it works... 100% of the time. HOWEVER, when I try to connect using my Galaxy S3 while on Wi-Fi I time out ~80% of the time. If I remove the timeout properties I get weird exceptions such as:
"recvfrom failed: ETIMEDOUT"
"failed to connect to <URL>: connect failed: ENETUNREACH (Network is unreachable)"
"unable to resolve the host <URL>: no address associated with hostname"
I'm open to any suggestions...
public static final String getHttpResponse(String url)
{
HttpURLConnection conn = null;
InputStream response = null;
try {
URL address = new URL(url);
conn = (HttpURLConnection)address.openConnection();
conn.setConnectTimeout(30 * 1000); //30 seconds
conn.setReadTimeout(30 * 1000); //30 seconds
response = conn.getInputStream();
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e("Util.getHttpResponse", Integer.toString(conn.getResponseCode()));
return null;
}
String result = Util.streamToString(response);
return result;
} catch(IOException e) {
response = conn.getErrorStream();
Log.e("Util.getHttpResponse", Util.streamToString(response));
return null;
} finally {
if( response != null ) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
conn.disconnect();
}
}
}
UPDATE:
- using AndroidHttpClient did not work
- After getting the input stream I had an error popup right in the eclipse IDE... As you can see my debug cursor made it all the way to line 107.. well after I was done getting the input stream this time...
I got the same problem on Android device. I use an IP address in the url. Final, I found the HttpURLConnection.connect(...) method involved the getHostName() internally. After that, I use the domain in the url, then it works 100% of the time.
As an experiment, what if you try using AndroidHttpClient class instead for doing the same? It has some predefined timeouts and other settings which, we were told, should work fine in most cases.

Categories

Resources