I want to get the source code of a web page that the users enters. When he presses the button, he should see the source in a TextView. This is my code:
final Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
URL url = null;
url = new URL(myEditText.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
myTextView.append(line);
}
} catch (Exception e) {
Log.e("ERR",e.getMessage());
}
}
});
When I run it I get a NullPointerException at
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
.-->Println needs a message.
I don't know what is wrong, since this is from a video tutorial. I have written <uses-permission android:name="android.permission.INTERNET"/> in Manifest so, everything should be allright.
try this.
url = new URL("http://www.stackoverflow.com");
if it works then you need to set validation for like isValidUrl() ?
Because user may have entered wrong URL.
if(!TextUtils.isEmpty(myEditText.getText()))
url = new URL(myEditText.getText().toString());
else
url="";
or if you are using latest version check StrictMode and remove it
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
also check the android is network available or not
Related
I'm making an android app for my final project at school.
I only know basic Java and I need to make my app connect to my mysql database.
So I followed this tutorial here with the get method:
https://www.tutorialspoint.com/android/android_php_mysql.htm
Aside from the php part and how it connects and execute the code what I don't understand is this line
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
I tried to read this:
https://developer.android.com/reference/java/lang/StringBuffer.html
But I suck at English and reading that won't make me understand what StringBuffer do a bit. I only know that it returns something and it is converted to string type so I think it is the php result.
What I want to know is what does StringBuffer do in the tutorial above? Like they return the value of the php result or not?
And if they do can I use it like this? Because I tried to do like this but got a catch (Exception e) with e.getMessage is null
TextView text2 = (TextView) findViewById(R.id.textView);
text2.setText(sb.toString());
If they do not, how can I set the result of the php value to my textview?
StringBuffer is a way of building a String piece by piece. It is an alternate to manually concatenating strings like this:
String string3 = string0 + string1 + string2;
You would instead do.
stringBuffer.append(string0)
.append(string1)
.append(string2);
Therefore, all it is doing is taking the Strings from in line-by-line and combining it into one String.
Well mate, it depends what result you are expecting you can connect to database for example to send or get some data, and then you need a php file as well.
But the easiest way to connect to db is to use Volley or AsyncTask.
Analise these sample code, it is fully working (but you need a php file which connects with your request:
private class YourTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://YOUR_PLACE_ON_A_SERVER_WHERE_THE_PHP_FILE_IS.php";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
//Here you can manage things you want to execute
}
I am totally new to Android but want to make a simple Android application that displays the state of my LEDs that I have on my breadboard. So far, I've used an ESP8266 to create a server that says "LED ON" (using this guide) and now I want to just display that string on my app in a textview or something.
Every helpful online resource I've seen uses the outdated apache HTTPClient method in Android Studio, but I need to use URLConnect on API 23. Below is what I have so far. When I try stepping through the code, the exception handler gets called when it executes the line starting with "BufferedReader", so I know there's something going on around there.
NOTE: I've added the following to my Android Manifest as well:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Anyone know what's going on, or can fix my code? Thanks for any help! As a beginner to Android programming, I really appreciate it! Below is the code in my .java file.
public void run ()
{
esp_message = (EditText)findViewById(R.id.esp_msg_txb);
btn_connect = (Button)findViewById(R.id.button);
btn_connect.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL("http://thing.local/led/1");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = in.readLine()) != null)
builder.append(inputLine.trim());
in.close();
String message = builder.toString();
esp_message.setText(message);
}
catch (Exception ex) {
Log.e("Fail 1", ex.toString());
//Toast.makeText(getApplicationContext(),"Invalid IP Address", Toast.LENGTH_LONG).show();
Log.i("Error on load data:", "" + ex.getMessage());
}
}
}).start();
}
}
);
}
Is there a simplest way to download small text string from URL like this one:"http://app.georeach.com/ios/version.txt"
In iOS its pretty simple. But for android em not finding something good. what is the method for getting text like that from the above URL??
I used this code in onCreate of hello app,n app crashed:
try {
// Create a URL for the desired page
URL url = new URL("http://app.georeach.com/ios/version.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder(100);
while ((str = in.readLine()) != null) {
sb.append(str);
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(sb.toString());
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
You have to create a new class extended from AsyncTask. You can't do network stuff in the main thread. It could work but you may not want to do that. Take a look at this link : http://developer.android.com/reference/android/os/AsyncTask.html
Also don't forget to add Internet permissions to your AndroidManifest.xml.
Try this:
URL url = new URL("http://bla-bla...");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
// your text is here
String text = sb.toString()
Do not forget to catch and handle IOException and close all streams.
An "easier" way would be this:
String url2txt = null;
try {
// Being address an URL instance
url2txt = new Scanner(address.openStream(), "UTF-8").useDelimiter("\\A").next();
} catch (IOException e) { ... }
The thing is what you consider "easier". As far as code goes, probably this is the shortest way, but it depends on what you want to do afterwards with the obtained text.
I use this code for read data from html page and put in to webview
public class MainActivity extends Activity {
public WebView objwebview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objwebview = (WebView)findViewById(R.id.webView1);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com");
try
{
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuilder str = new StringBuilder();
while((line = reader.readLine()) != null) {
str.append(line);
}
objwebview.loadData(str.toString(), "text/html", "UTF-8");
}
catch(Exception e)
{
e.printStackTrace();
objwebview.loadData(e.toString(), "text/html", "UTF-8");
}
but when I run that ,I give this error ("android.os.networkonmainthreadexception")
how can I fix that?
You are running your networking code on the main thread in Android. Read this to find some partial answers to your problem.
The basic idea is that if you perform synchronous reads that do not immediately return (i.e., things that take a long time, such as network operations), you need to do so on another thread, and then communicate the results back to the GUI.
You have a few options to do this: you can use an AsyncTask, which allows you to painlessly publish updates to the UI, or you can use a background Service along with an associated communication (either via AIDL or a simpler Message and Handler).
you are accessing network connection in main thread. paste the following lines beneath setContentView(your_layout);
// Allow network access in the main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
I'm new here and I wish I won't make any bloomer :)
I'm developing some android app and have stucked in connecting to other computer, where I've installed ASP.net page. I can't emulate it due to problems with connecting to host.
The code that I'm using:
public class SPCChartViewerActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String strData = urlData("http://[server]/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(strData);
}
private String urlData(String urlString){
URLConnection urlConnection = null;
URL url = null;
String string = null;
try {
url = new URL(urlString);
urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while((string = reader.readLine()) != null){
stringBuffer.append(string + "\n");
}
inputStream.close();
string = stringBuffer.toString();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return string;
}
}
In tag [server] I've put:
that computer's name: http://miltstx155srv01/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS
In this case I receive java.net:UnknownHostException
that computer's IP: http://10.72.152.163/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS
In this case I receive java.net:FileNotFoundException
If I ommit the "http://" I receive java.net:Protocol Not Found
Ok, maybe something with my company's DNS. So I've put this page on my computer, which is also running AVD emulator. So the url is now: http://10.0.2.2/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS - but still java.net:UnknownHostException.
Of course clause uses-permission android:name="android.permission.INTERNET" is added to manifest.
Still, every example written upper works fine with webbrowser (of course except 10.0.2.2 - but changing it to localhost makes it work).
No idea, I've spent whole day testing it. Can anyone help?