android 4.3 - BufferedReader shows Please Wait message - android

I have the following function to allow my android app to communicate with a web server. However the app shows a 'Please Wait' message when I call this code and only disappears if a new activity loads in or if I press the back button. Where is the Please wait coming from and how can I avoid it appearing? Thanks
package util.sapa.sapacontainermanager5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class SimpleWebCalls {
public String executeHttpGet(String serverIP, String nvp) {
String lines="";
serverIP="???????????";
URL url = null;
try {
url = new URL("http://" + serverIP + "/WCF.aspx?" + nvp);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
try {
conn.setRequestMethod("GET");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
lines+=line;
}
in.close();
return lines;
} catch (IOException e) {
e.printStackTrace();
}
} catch (ProtocolException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
}
the above class is called from:
public String GetDataFromServer(String serverIP,String nvp) {
SimpleWebCalls tWebCall = new SimpleWebCalls();
String sReturn="";
sReturn= tWebCall.executeHttpGet(serverIP,nvp);
return sReturn;
}
the above function is called from:
String data="";
data="doAction=location&u=" + sess.getUserName()+
"&p=" + sess.getPwd() +
"&uid=" + sess.getUserID() +
"&lf=" + sess.encodeStr(editScannedCode.getText().toString());
result = sess.GetDataFromServer(serverIP,data);

follow this tutorial link it might be helpful to you.
add GetDataFromServer() method in to your doInBackground() method.

Related

How to resolve android.os.networkonmainthreadexception

I am new to android and I am trying to read data from a server. I use a util and call that util like this
private void ParseSource(String Url){
String source = new Cls_SourceGrabber().grabSource(Url);
}
But I am getting a android.os.networkonmainthreadexception. How can I reduce that?
My SourceGrabber util:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Cls_SourceGrabber {
private HttpGet mRequest;
private HttpClient mClient;
private BufferedReader mReader;
private StringBuffer mBuffer;
private String mNewLine;
public Cls_SourceGrabber() {
mRequest = new HttpGet();
InitializeClient();
mReader = null;
mBuffer = new StringBuffer(10000);
mNewLine = System.getProperty("line.separator");
}
private void InitializeClient() {
if (mClient == null || mClient.getConnectionManager() == null) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 4500);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
// HttpConnectionParams.setTcpNoDelay(httpParameters, true);
mClient = new DefaultHttpClient(httpParameters);
}
}
/*
*Grab the full source
*/
public String grabSource(String url) {
mBuffer.setLength(0);
InitializeClient();
String source = "";
try {
mRequest.setURI(new URI(url));
HttpResponse response = mClient.execute(mRequest);
mReader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = mReader.readLine()) != null) {
mBuffer.append(line);
mBuffer.append(mNewLine);
source = mBuffer.toString();
if (Thread.interrupted()) {
break;
}
}
} catch (ConnectTimeoutException e) {
source = "Connection Timed Out.";
} catch (java.net.UnknownHostException e) {
source = "No Internet Connection available!";
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
source = "Site Parsing Exception.";
} catch (ClientProtocolException e) {
source = "Protocol Exception.";
} catch (IOException e) {
source = "Server not responding.";
} catch (URISyntaxException e) {
source = "Wrong URL!";
} catch (Exception e) {
source = "Exception - " + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
closeReader();
}
return source;
}
}
First of all, I would not recommend on using HTTPClient any more, since it is not supported any more from sdk version 23.
So, it will be better to migrate the network operations to URL Connection.
Now, android never allows network operations on Main thread since it will block the UI thread for a considerable time, hence may cause crash or bad user experience.
You can take a look on these docs : Doc 1
The better way to do Network operations is by creating an AsyncTask.
Just take care not to access any UI thread element in the doInBackground method. You can modify UI Thread elements on onPreExecute or onPostExecute Methods.
I have created a NetworkOps Util. You can take a look on that, whether it may be any use for you :
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.csehelper.variables.Constants;
import com.csehelper.variables.Keys;
import com.csehelper.variables.Url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
public class NetworkOps {
public final String EXCEPTION = "~Exception~";
/****************************
* Method to Grab Source
****************************/
public static String GrabSource(String URL) {
return PostData(URL, null);
}
/**
* *****************************************
* Method to Grab Source code from URL
* Posting Data
* *****************************************
*/
private static String PostData(String url, Uri.Builder uribuilder) {
String Source;
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(10000);
if(uribuilder != null) {
String query = uribuilder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Source = builder.toString();
} else {
Source = EXCEPTION + "Server unreachable. Check network connection.";
}
} catch (SocketTimeoutException e) {
Source = EXCEPTION + "Connection timed out.";
} catch (java.net.UnknownHostException e) {
Source = EXCEPTION + Constants.EXCEPTION_NO_NET;
} catch (ArrayIndexOutOfBoundsException e) {
Source = EXCEPTION + "Server error";
} catch (ProtocolException e) {
Source = EXCEPTION + "Protocol error";
} catch (IOException e) {
Source = EXCEPTION + "Server unreachable. Check network connection.";
} catch (Exception e) {
Source = EXCEPTION + "Error:" + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return Source;
}
}
Call these Static Functions from AsyncTask:
/*********************************
* AsyncTask to GrabSource
********************************/
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> {
String Source = null;
String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json";
#Override
protected void onPreExecute() {
//Runs on Main Thread. You can access your UI elements here.
}
#Override
protected Void doInBackground(Void... params) {
// Don't access any UI elements from this function
Source = NetworkOps.GrabSource(this.url);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Source != null) {
if (!Source.contains("~Exception~")) {
//Show Error Message or do whatever you want
} else {
//Do Whatever with your Grabbed Sourcecode.
// This function runs on UI Thread, so you can update UI elements here
}
}
}
You can also post data with the function PostData. In method doInBackground, add this:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", "value")
.appendQueryParameter("key2", "value2");
Source = NetworkOps.PostData(getApplicationContext(), url, builder);

NetworkOnMainThreadException android activity [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 6 years ago.
I am using this code to retrieve website data inside android activity.It is throwing android.os.networkonmainthreadexception
try
{
URL url = new URL("https://enigmatic-woodland-35608.herokuapp.com/pager.json");
URLConnection tc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line, newl = " ";
while ((line = in.readLine()) != null) {
newl += line.trim();
}
System.out.println("newl" + newl.trim());
} catch (Exception e) {
Log.e("exception", e.toString());
}
Please give me a possible solution..
Network oprations/call cannot be done in main thread. You need to run it from another thread , asynchronous task or an intent service
Note : All UI opration shoud be done onPostExecute,onPreExecute
The below code may help you to solve.
Call AsyncTask where you want
new PagerAsyncTask().execute();
class PagerAsyncTask extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb=null;
BufferedReader reader=null;
String serverResponse=null;
try {
URL url = new URL(""https://enigmatic-woodland-35608.herokuapp.com/pager.json"");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
int statusCode = connection.getResponseCode();
//Log.e("statusCode", "" + statusCode);
if (statusCode == 200) {
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
connection.disconnect();
if (sb!=null)
serverResponse=sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return serverResponse;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//All your UI operation can be performed here
//Response string can be converted to JSONObject/JSONArray like
JSONObject response=new JSONObject(s);
System.out.println(s);
}
}
Network operations can involve unpredictable delays. To prevent this
from causing a poor user experience, always perform network operations
on a separate thread from the UI.
Please check the doc.
I am using a NetworkOps util in my projects. Try it:
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.csehelper.variables.Constants;
import com.csehelper.variables.Keys;
import com.csehelper.variables.Url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
public class NetworkOps {
public final String EXCEPTION = "~Exception~";
/****************************
* Method to Grab Source
****************************/
public static String GrabSource(String URL) {
return PostData(URL, null);
}
/**
* *****************************************
* Method to Grab Source code from URL
* Posting Data
* *****************************************
*/
private static String PostData(String url, Uri.Builder uribuilder) {
String Source;
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(10000);
if(uribuilder != null) {
String query = uribuilder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Source = builder.toString();
} else {
Source = EXCEPTION + "Server unreachable. Check network connection.";
}
} catch (SocketTimeoutException e) {
Source = EXCEPTION + "Connection timed out.";
} catch (java.net.UnknownHostException e) {
Source = EXCEPTION + Constants.EXCEPTION_NO_NET;
} catch (ArrayIndexOutOfBoundsException e) {
Source = EXCEPTION + "Server error";
} catch (ProtocolException e) {
Source = EXCEPTION + "Protocol error";
} catch (IOException e) {
Source = EXCEPTION + "Server unreachable. Check network connection.";
} catch (Exception e) {
Source = EXCEPTION + "Error:" + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return Source;
}
}
Call these Static Functions from AsyncTask:
/*********************************
* AsyncTask to GrabSource
********************************/
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> {
String Source = null;
String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json";
#Override
protected void onPreExecute() {
//Runs on Main Thread. You can access your UI elements here.
}
#Override
protected Void doInBackground(Void... params) {
// Don't access any UI elements from this function
Source = NetworkOps.GrabSource(this.url);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Source != null) {
if (!Source.contains(EXCEPTION)) {
//Show Error Message or do whatever you want
} else {
//Do Whatever with your Grabbed Sourcecode.
// This function runs on UI Thread, so you can update UI elements here
}
}
}
You can also post data with the function PostData. In method doInBackground, add this:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", "value")
.appendQueryParameter("key2", "value2");
Source = NetworkOps.PostData(getApplicationContext(), url, builder);

Basic android http get

I'm a android noob on programming, but with some help of a few programms I can learn the basics. I would like to do a basic http get request to an arduino ethernetshield.
For this I've found some code, but I can't get it to work.
I'm allways stuck on the getResponse part with the code I've tried from several pages.
I've found the following page which gave me readable code:
How to work with an image using url in android?
Now I've created the following:
Press on a button and do a get to an url:
package adhttpget.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class AdhttpgetActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pushbutton1(View view) {
Toast.makeText(getBaseContext(), "button press", Toast.LENGTH_SHORT).show();
Log.e("button", "pressed");
URL connectURL = new URL("http://192.168.0.48/?out=13&status=2");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn); // <-- THIS IS MY PROBLEM
}
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e("http", "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
}
Where can I find information to learn how to write the code correctly?
Or do you happen to have the answer in some kind of hint so I can learn from it?
You must create a BufferedReader passing the InputStream, then you can read strings
private static String convertStreamToString(InputStream is) {
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();
}
}
return sb.toString();
}
Then I recommend you make the connection (or read/write file) with a separeted thread from the Thread UI (use Thread, AsyncTask, Handler, etc) because that will improve your app.
http://developer.android.com/intl/es/guide/components/processes-and-threads.html

Android: Is there a way to change MediaPlayer urls?

is there a way to change the urls without compiling the app or deployment once i pushed to the market? the url might change in future or point to different urls.
currently i am hardcoding the urls somethign like this:
try {
url = "http://ofertaweb.ro/android/sleepandlovemusic/" + songs_array[counter] + ".mp3";
mediaPlayer.setDataSource(url);
}
Do not hardcode your URL at project build time, consider writing code that dynamically resolve it at application run time. for example, you can create a static html page (contains a list of actual mp3 URLs), hardcode this static html page URL at project build time, every time your application starting running, query this static html page to get the up-to-date mp3 URL at application run time. there are many alternative way to achieve this, just give you some clue, hope this helps.
here is what i found a way to read the html file:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Get_Webpage {
public String parsing_url = "";
public Get_Webpage(String url_2_get){
parsing_url = url_2_get;
}
public String get_webpage_source(){
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(parsing_url);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
String html = "";
InputStream in = null;
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e) {
} catch (IOException e) {
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
try {
while((line = reader.readLine()) != null)
{
str.append(line);
}
} catch (IOException e) {
}
try {
in.close();
} catch (IOException e) {
}
html = str.toString();
return html;
}
}
then you read like this:
try {
Get_Webpage obj = new Get_Webpage("http://ofertaweb.ro/android/sleepandlovemusic/list_files.php");
directory_listings = obj.get_webpage_source();
} catch (Exception e) {
}
//Log.d("director listing", directory_listings);
songs_array = directory_listings.split(":::");

UrlConnection working with Java code but not for Android - use in Digest Authenticated Server

I'm using URLConnection to connect to the main server. The server implements digest authentication. If I connect to the server with java library, the connection is successful. But if I use the same code for android, the connection is rejected for the reason - username and password do not match.
Here is the code for my Java project:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
public class Connect {
static StringBuilder sb;
public static void main(String args[]) {
String strURL = "http://hostserver/";
final String username = "username";
final String password = "password";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication (username, password.toCharArray());
System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
return pa;
}
});
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(strURL);
URLConnection connection = url.openConnection();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (java.net.ProtocolException e) {
sb.append("User Or Password is wrong!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
System.out.println("Exception");
}
}
System.out.println("The Data is: " + sb.toString());
}
}
The above code works fine and I'm able to connect to my host server which is implementing digest authentication. I'm unable to use the same code for Android to connect. Here is my android code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class Connect extends Activity {
static StringBuilder sb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String strURL = "http://hostserver/";
final String username = "username";
final String password = "password";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication (username, password.toCharArray());
// System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
return pa;
}
});
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(strURL);
URLConnection connection = url.openConnection();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (java.net.ProtocolException e) {
sb.append("User Or Password is wrong!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
System.out.println("Exception");
}
}
Log.d("DATA", sb.toString());
}
}
If the same code works for Java, it should also work for Android.
The code loops in the Authenticator as it finds username and password not matching in the Android code for some reason which in fact are correct. The code runs perfect for Java project.
while ((line = in.readLine()) != null) {
sb.append(line);
}
remove this code and write just
line = in.readLine().toString();
sb.append(line);
Check Issue 9579: Connection to server with Digest Authentication not working.
http://bethecoder.com/applications/tutorials/tools-and-libs/commons-http-client/digest-authentication.html
I found this site to be helpful.

Categories

Resources