getting the html source code with a url in an android application - android

I was trying to write some codes that takes in a url from the user and after which when the submit button is clicked, I will take the url and make a call and retrieve the html source code from the page. However, I have gotten a exception of the following:
W/System.err(14858): android.os.NetworkOnMainThreadException
W/System.err(14858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
It seems that for android 3.0 the platform that I am trying to development on doesn't allow me to use the network resources on the main method. I understand that there are methods such as running it in the background or use the async method should work, but can anyone guide me on this? I'm not too sure on how to go about it. I'm new to programming.
Thanks in advance.
Below is my current code, on the onclick method:
String htmlCode = "";
try {
URL url = new URL("http://www.google.com");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode += inputLine;
Log.d(LOG_TAG, "html: " + inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Error: " + e.getMessage());
Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
}

You could use a Runnable or Thread, but probably the most idiomatic Android way to do this is to use an AsyncTask.
new AsyncTask<String, Void, String>(){
#Override
protected String doInBackground(String... urlStr){
// do stuff on non-UI thread
StringBuffer htmlCode = new StringBuffer();
try{
URL url = new URL(urlStr[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode += inputLine;
Log.d(LOG_TAG, "html: " + inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Error: " + e.getMessage());
Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
}
return htmlCode.toString();
}
#Override
protected void onPostExecute(String htmlCode){
// do stuff on UI thread with the html
TextView out = (TextView) findViewById(R.id.out);
out.setText(htmlCode);
}
}.execute("http://www.google.com");

Related

HTTP POST REQUEST To PHP Server Android Studio

public class MainActivity extends AppCompatActivity {
EditText editmsg , editmail ;
TextView content ;
String Message , Email ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editmsg = (EditText) findViewById(R.id.editMessage);
editmail = (EditText) findViewById(R.id.editMail);
Button btnsubmit = (Button) findViewById(R.id.btnSubmit);
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
GetText();
} catch (Exception ex) {
content.setText(" Url Exception!");
}
}
});
}
public void GetText()throws UnsupportedEncodingException {
Message = editmsg.getText().toString();
Email = editmail.getText().toString();
String data = URLEncoder.encode("message", "UTF-8")
+ "=" + URLEncoder.encode(Message, "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "="
+ URLEncoder.encode(Email, "UTF-8");
String text = "";
BufferedReader reader=null;
HttpURLConnection urlConnection = null;
try
{
// Defined URL where to send data
URL url = new URL("http://nitesh.com/feedback/add.php");
// Send POST data request
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response on activity
content.setText( text );
}
}
I dont know what is wrong with code when i click the send button it showing Unfortunately,HTTP has stop (looking just like app crashed).
please review my code and tell me what i have done wrong.
One thing I see at once is that you are making your request in main UI thread (in onCreate). This is not allowed because network connections usually take some time to finish. There should also be an error message in the logcat about this.
What you should do is make your request in a separate thread. You can accomplish this by using AsyncTask, or Thread. Google it.
UPD:
Example on how to use Threads in Java. The method run will be executed asynchronously.
new Thread(new Runnable(){
#Override
public void run(){
GetText();
}
}).start();
Next time, please include the logcat errors in the question.
Consider using http://square.github.io/retrofit/ for network communication.
You will get a simple api and all request will be wrapped into correct thread.
You can accomplish this task by using AsyncTask

How are privacy policies done?

I am curious about the proper way of doing privacy policies if displaying natively in a mobile app? I can create a string constant, however, it seems like it would be easier to add as a text file and then read from the text file. This is what I wanted to do, however, the text that should be hyperlinked would not be hyperlinked.
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
So how is everyone doing this?
Well, if you plan on your policy changing you'd want to pull it off a database or something.

Android HTTP connection and stream "gathering"

I "wrote" some code which should execute http request + stream download, however it does not seem to be working with the second part. It connects to the server, but without getting the expected data from it. The first few times it evena worked out, it displayed the html data from google, but afterwards,
I tried to optimize my code and threw something away, added something here and there, extended it by a class etc., which probably caused the "error". Here is my code:
public class MainActivity extends ActionBarActivity {
private static final String TAG = null;
TextView httpStuff;
public static String info;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AsyncDownload data = (AsyncDownload) new AsyncDownload().execute();
info = data.get();
httpStuff.setText(info);
} catch (Exception e){
e.printStackTrace();
}
}
public class AsyncDownload extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
Log.v(TAG, "Final Requsting URL is : :" + "google.com");
String line = "";
String responseData = null;
try {
StringBuilder sb = new StringBuilder();
String x = "";
URL httpurl = new URL("http://www.google.com");
URLConnection tc = httpurl.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(tc.getInputStream()));
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
x = sb.toString();
}
responseData = new String(x);
}
catch (UnknownHostException uh){
Log.v("NewWebHelper", "Unknown host :");
uh.printStackTrace();
}
catch (FileNotFoundException e) {
Log.v("NewWebHelper", "FileNotFoundException :");
e.printStackTrace();
}
catch (IOException e) {
Log.v("NewWebHelper", "IOException :");
e.printStackTrace();
}
catch (Exception e) {
Log.v("NewWebHelper", "Exception :");
e.printStackTrace();
}
return responseData;
}
}
I just don't know what's the missing thing. I've been trying to solve this for hours with a big variety of data-passing versions of this, but nothing seems to be working. I'm counting on you, brainiacs.

Why AsyncTask doesn't show result first time?

I have a text file on a server (right now on a local server by WAMP in c:/wamp/www/android/sample.txt ) and an android application with 3 activity that read data through the WiFi.
The first one get the address (on local host use 10.0.2.2/android/sample.txt) and go to activity2. In activity2 I have a button that goes to activity3.
code is third activity:
private InputStream OpenHttpConnection(String urlString) throws Exception {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
throw new IOException("NOT an HTTP Connection!");
}
try {
HttpURLConnection httpCon = (HttpURLConnection) conn;
httpCon.setAllowUserInteraction(false);
httpCon.setInstanceFollowRedirects(true);
httpCon.setRequestMethod("GET");
httpCon.connect();
response = httpCon.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpCon.getInputStream();
Log.d("myerr", response + "");
}
} catch (Exception e) {
Log.d("myerr2", e.getLocalizedMessage());
throw new IOException("Error Connection!");
}
return in;
}
private String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (Exception e) {
Log.d("myerr", e.getLocalizedMessage());
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String
.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (Exception e) {
Log.d("myerr", e.getLocalizedMessage());
return "";
}
return str;
}
private class DownloadTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
protected void onPostExecute(String result) {
Global.readedDataFromFile=result;
//Toast.makeText(DrawRhActivity.this,"Result: "+Global.readedDataFromFile, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_rh);
String user_address = Global.ip_address;
new DownloadTextTask().execute(user_address);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Value: " + Global.readedDataFromFile);
}
I also define some global variable in Global.java .
AND HERE IS MY PROBLEM:
The 3rd activity doesn't show data on textview at the first time. but when I back to 2nd activity and hit the button my data loaded.
Why AsyncTask doesn't show result first time and how to fix this?
Thanks for your attention.
tv.setText("Value: " + Global.readedDataFromFile);
write this line in onPostExecute
protected void onPostExecute(String result) {
Global.readedDataFromFile=result;
//Toast.makeText(DrawRhActivity.this,"Result: "+Global.readedDataFromFile, Toast.LENGTH_LONG).show();
tv.setText("Value: " + Global.readedDataFromFile);
}
Solution:
put tv.setText("Value: " + Global.readedDataFromFile); in your onPostExecute method.
Explaination:
AsyncTask runs on separate thread instead of your UI thread.
so when it is being executed Global.readedDataFromFile may be empty.and when execution completes it goes in onPostExecute method and now Global.readedDataFromFile have some value stored in it.
Issue:
you are setting the text instantly after calling new DownloadTextTask().execute(user_address);
so it may happen that the AsyncTask is not completed yet and Global.readedDataFromFile is empty.
Reference:
AsyncTask
I hope it will be helpful !!
the problem lies within your onCreate function:
String user_address = Global.ip_address;
new DownloadTextTask().execute(user_address);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Value: " + Global.readedDataFromFile);
First you start a task, then you want to set your views, but your task is not finished.
You have to set the views with the result of your task in to onPostExecute of the task.
Keep your DownloadTextTask &
Trying this code in your Activity
DownloadTextTask textTask = new DownloadTextTask();
textTask.execute(user_address);
String strDownloaded = "";
try {
strDownloaded = textTask.get();
} catch (Exception e) {
Log.e("DownloadTextTask", "Error: " + e.getMessage());
}

AsyncTask returns null in OnPostExecute

I'm trying to get text from a .txt located on a server to a string (feed_str)
My code:
public class getFeedData extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params)
{
String feed_str = null;
try
{
// Create a URL for the desired page
URL url = new URL("http://www.this.is/a/server/file.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((feed_str = in.readLine()) != null)
{
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
}
catch (MalformedURLException e)
{
System.out.println("AsyncError: " + e);
}
catch (IOException e)
{
System.out.println("AsyncError: " + e);
}
catch (NullPointerException e)
{
System.out.println("AsyncError: " + e);
}
return feed_str;
}
#Override
protected void onPostExecute(String feed_str)
{
super.onPostExecute(feed_str);
System.out.println("onPostExecute " + feed_str);
}
With this code the logcat should output something like: "onPostExecute text from server" but instead of that it outputs "onPostExecute null"
Any ideas how to fix?
Btw: The url has been checked with a browser and the text was displayed so the url isn't the problem.
This loop doesn't exit until feed_str == null. So, the last value of it is null, which is what you return.
while ((feed_str = in.readLine()) != null)
{
// str is one line of text; readLine() strips the newline character(s)
}
You need to keep a "total" String also, if that's what you want to return.
String entireFeed = "";
while ((feed_str = in.readLine()) != null)
{
entireFeed += feedStr + "\n";
// whatever else you're doing
}
...
return entireFeed;

Categories

Resources