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();
}
});
Related
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.
This question already has answers here:
FileNotFoundException while getting the InputStream object from HttpURLConnection
(8 answers)
Closed 6 years ago.
My code to that sends JSON over the network works until OutputStream is invoked, but when I try actually sending the data, I get the following exception. Can anyone help me figure it out?
java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.accept);
textView = (TextView) findViewById(R.id.textView);
editName = (EditText) findViewById(R.id.editName);
editCountry = (EditText) findViewById(R.id.editCountry);
editTwitter = (EditText) findViewById(R.id.editTwitter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(MainActivity.this);
httpAsyncTask.execute("http://hmkcode.appspot.com/jsonservlet", editName.getText().toString(), editCountry.getText().toString(), editTwitter.getText().toString());
}
});
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private MainActivity mainActivity;
String result = "";
HttpAsyncTask(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
protected String doInBackground(String... strings) {
Person person = new Person();
person.setName(strings[1]);
person.setCountry(strings[2]);
person.setTwitter(strings[3]);
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "!!!");
jsonObject.accumulate("country", "###");
jsonObject.accumulate("twitter", "####");
json = jsonObject.toString();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("content-type", "application/json");
InputStream is = httpURLConnection.getInputStream();
OutputStream os = httpURLConnection.getOutputStream();
os.write(json.getBytes("utf-8"));
os.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
str = result;
mainActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(str);
mainActivity.textView.setText(jsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
W/System.err: java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
W/System.err: at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
.....
This is equivalent to HTTP status 404 - Not Found.
I am trying to display main and description from json data i take from opneweathermap. And nothing happen, but I don't have errors.
I will not include the link.
Here is my MainActivity class
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mTextView = (TextView) findViewById(R.id.textView2);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask task = new DownloadTask();
task.execute("Link");
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while(data != -1){
char current = (char) data;
result+=current;
data = inputStreamReader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Toast.makeText(getApplicationContext(), "Soem"+message,Toast.LENGTH_LONG).show();
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i=0;i<array.length();i++){
JSONObject jsonPart = array.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != ""){
message += main + ": " + description + "\r\n";
}
}
if(message != ""){
mTextView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I have included uses-permissions and i have TextView and Button that will display the data from json in my layout file.
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();
}
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);
}
}