Reputation: 11
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.
Upvotes: 1
Views: 806
Reputation: 36289
This task can be completed much easier using my 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.");
}
}));
Upvotes: 1
Reputation: 97
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.
Upvotes: 0