android network connection faliure - java

I'm having a hard time to connect the application to the internet and retrieve the html source.
Been looking all over for a solution and didn't find. Hope someone could help.
Here is my code:
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText et = (EditText) findViewById(R.id.editText1);
final Button b = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
URL url=null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
tv.append(line);
}
} catch (Exception e) {
}
}
});
}
I've also added INTERNET permission..

You need to move the code which connects to the internet and fetches data to an AsyncTask. This is because of the NetworkOnMainThreadException. This exception is thrown when an application attempts to perform a networking operation on its main thread.
Though there is a workaround available by using the StrictMode.ThreadPolicy, it highly advisable not to do that.
Here is a excerpt from the docs.
NetworkOnMainThreadException:-
This is only thrown for applications
targeting the Honeycomb SDK or higher. Applications targeting earlier
SDK versions are allowed to do networking on their main event loop
threads, but it's heavily discouraged.
See this question for more info.

Because you are doing this on UI therad.
Try this:
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText et = (EditText) findViewById(R.id.editText1);
final Button b = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread th = new Thread() {
#Override
public void run() {
try {
URL url=null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
tv.append(line);
}
} catch (Exception e) {
}
}
};
th.start();
}
});
}

i will suggest you to use AsyncTask
Do this
On ButtonClick
RequestClient reqClient = new RequestClient(ActivityName.this);
String AppResponse = null;
AppResponse = reqClient.execute().get();
RequestClient
public class RequestClient extends AsyncTask<String, Void, String> {
Context context;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
is.close(); // Close the stream
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
client.getConnectionManager().shutdown();
return responseString.trim();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}

Related

Refresh json url when button pressed

I found out how i did what i asked in an earlyer question but i am wondering how i can reload URL url = new URL("https://www.lurkinator.net/api/data?username="+typedText+""); After the user presses a button? I have a button called "button" i want it to refresh the url since i have the typedText at the end and when user edits the edittext i want data to refresh from the api
Here is my code. And here is a screenshot of how the app looks so you have an idea.
Photo
public class MainActivity extends AppCompatActivity {
TextView points, username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points = (TextView) findViewById(R.id.textView8);
username = (TextView) findViewById(R.id.textView9);
new getData().execute();
}
class getData extends AsyncTask<String, String, String> {
// get EditText by id and store it into "inputTxt"
EditText USERNAME = (EditText) findViewById(R.id.UserSet);
// Store EditText - Input in variable
String typedText = USERNAME.getText().toString();
HttpURLConnection urlConnection = null;
#Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://www.lurkinator.net/api/data?username="+typedText+"");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String line;
while ((line = br.readLine()) != null) {
result.append(line+"\n");
}
br.close();
String jsonString = result.toString();
System.out.println("JSON: " + jsonString);
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String t = jsonObject.getString("points");
String u = jsonObject.getString("username");
points.setText(t);
username.setText(u);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Thanks!
Add ok button click listener
Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
new getData().execute();
}
});

Cant get Json info on the app [duplicate]

This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
Closed 5 years ago.
Im just a beginner learning Json parsing and stream from the net,
well I dont get errors in this app but it doesnt display anything.
I dont know what the problem and cant see any problem in the log.
here is the code:
InputStream is;
String line;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
try {
URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&minlatitude=4&maxlatitude=5");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
if(connection.getInputStream()==null)
{
textView.setText("input stream empty");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
while((line=reader.readLine())!=null){
builder.append(line);
}
if(builder.toString().equals(""))
{
textView.setText("no work builder empty");
}
line=builder.toString();
JSONObject object = new JSONObject(line);
JSONArray fea = object.getJSONArray("features");
JSONObject QUAKE = fea.getJSONObject(0);
JSONObject pro = QUAKE.getJSONObject("properties");
int mag = pro.getInt("mag");
textView.setText(mag+"");
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks!
A exception is thrown when an application attempts to perform a networking operation on its main thread. Hence the network call wouldn't take place in your case as you are making a network call on main thread and it would directly throw a NetworkOnMainThreadException instead of making a network call. Run your code in AsyncTask
well doing any network operation on main thread is crime in Android. You will be punished with network_operation_on_main_thread exception. You need take help from AsyncTask.
please try below code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
String data = "input stream empty";
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&minlatitude=4&maxlatitude=5");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
while((line=reader.readLine())!=null){
builder.append(line);
}
if(builder.toString().equals(""))
{
data = "no work builder empty";
}
line=builder.toString();
JSONObject object = new JSONObject(line);
JSONArray fea = object.getJSONArray("features");
JSONObject QUAKE = fea.getJSONObject(0);
JSONObject pro = QUAKE.getJSONObject("properties");
int mag = pro.getInt("mag");
data = mag+"";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
textView.setText(data);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}

Asking the user for a URL to receive a JSON

Just as a practicing exercise i'm trying to make an app that fetches a JSON from a URL.
I found the following code in other thread here in stackoverflow and it works just fine. My problem is that the URL is hardcoded, and i need it to be an input by the user. What should i change/add?
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("Url address here");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response..... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
This is the thread where i got that code from:
Get JSON Data from URL Using Android?
Create a constructor in your async Task
private class JSONTask extends AsyncTask<String, String, String> {
String url;
public JSONTask(String url){
this.url=url;
}
use the url string in place of params[0]
And wherever you call your async task do it like this
new JSONTask(textView.getText()).execute()
This should solve it.
Else you can directly use the do in background variable params.
So the problem is that you are using a TextView. TextView does not recieve inputs.
EditText does.
Make these Changes:
TextView txtJson;
In your OnCreate change this:
txtJson = (EditText) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute(txtJson.getText());
}
});
Now in your xml file change the Button to EditText.
Hope this helps.

Android HTTP API call

I am pretty fresh with Android Studio, and I am trying to call MVC Api service with api key and app id.
However, whenever i try the one with api key and app id, it always throws "Trust anchor for certification path not found." while it works good when i try the one without api key.
Can you give me a advice? Thank you.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.button);
tv = (TextView)findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
new JSONTask().execute("");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
try{
StringBuilder result = new StringBuilder();
URL url2 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Apikey",key);
conn.addRequestProperty("AppID",id);
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
catch (IOException e)
{
Log.e("MYAPP", "exception", e);
return "error";
}
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
tv.setText(result);
}
}
This kind of exceptions mostly occur because of the misconfiguration of a web service. Check out this article. It's fully described why you are getting this exception.

AsyncTask dont show me message from server (HttpUrlConnection)

So I'm trying to read a message from the server by HttpURLConnection in a AsyncTask class. The problem is, when i send the request to read the data from the server, it just keeps displaying the ProgresssDialog, like it doesn't read the data from the server:
public class MainActivity extends Activity{
EditText name, password;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String serverURL = "http://192.168.1.1/my/text.php";
LongOperation longOperation = new LongOperation();
longOperation.execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private String content;
private String error = null;
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
#Override
protected void onPreExecute() {
uiUpdate.setText("Output : ");
dialog.setMessage("Downloading source..");
dialog.show();
}
#Override
protected Void doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
client.disconnect();
} catch (IOException e) {
error = e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
if (error != null) {
uiUpdate.setText("Output : "+error);
} else {
uiUpdate.setText("Output : "+content);
}
}
I already tryed before the connectivity to server via HttpClient, so thats not the problem.Thanks!
Try debugging it and see if OnPostExecute() method is getting called or not.!
This seems to get stuck in your stream reader code. Also, add a connection timeout of, say, 5-10 seconds for better user experience.!
Moreover, there seems to be an issue with your return type of doInBackground() method and input parameter type of OnPostExecute() method. As per your AsyncTask definition, they both should be string, isnt it?
See this
Try remove client.connect();
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
//remove client.connect();
int response = client.getResponse();
if(response == HttpURLConnection.HTTP_OK){
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
}
finally{
client.disconnect();
}
} catch (IOException e) {
error = e.getMessage();
}
return null;
Make sure your server is running. Also set request time out.
You are not always required to explicitly call the connect method to initiate the connection. Operations that depend on being connected, like getInputStream, getOutputStream will implicitly perform the connection, when necessary.
This link
Try this:
private class LongOperation extends AsyncTask<String, Void, String>
{
private String content;
private String error = null;
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
#Override
protected void onPreExecute() {
uiUpdate.setText("Output : ");
dialog.setMessage("Downloading source..");
dialog.show();
}
#Override
protected Strinh doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection(); client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
//client.discon dialog.dismiss();
}
catch (IOException e)
{
content = e.getMessage();
}
return content ;
}
#Override
protected void onPostExecute(String returnValue) {
if (return value != null) {
uiUpdate.setText("Output : "+error);
}
else {
uiUpdate.setText("Output No Value Returned");
}
dialog.dismiss();
}

Categories

Resources