I can't figure out how to make this code work in an AsyncTask, I searched for multiple examples but it keeps crashing. I found this simple code on the internet and I want to adapt it to get the URL from a textfield and get the HTML code. I found out it has to be in an AsyncTask otherwise it won't work but even in an AsyncTask I can't get it to work. Here's my code:
String ETURL = ETURLInput.getText().toString();
try {
URL TestURL = new URL(ETURL);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(TestURL.openStream()));
String outputCode;
while ((outputCode = bufferReader.readLine()) != null)
TVCode.setText(outputCode);
bufferReader.close();
} catch (Exception e) {
TVCode.setText("Oops, something went wrong.")
}
}
This is the code which needs to be executed inside an ActionListener. So when I click the button it should execute this code in an AsyncTask.
Hopefully somebody could help me with this.
You forgot to add openConnection, add this: URLConnection conn = TestURL.openConnection(); after creating your URL object.
To make it work with an asynctask, what you can do is storing your string in a class variable, returning it in the doInBackGround and using it in your onPostExecute.
An example of method you can create in your asynctask:
protected String getContentUrl(String URL) {
String line=null;
String result="";
try {
try {
URL url;
// get URL content
url = new URL(URL);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
line=br.readLine();
while (line!= null) {
result=result+line;
line=br.readLine();
}
//System.out.print(result);
br.close();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
Then you get your result this way on doInBackGround:
getContentUrl(YOUR URL HERE)
Store this value in a String, and return it. Then you can use it in your onPostExecute
Hope it helps :)
Related
I using the class async to download and upload data in two activitys. The upload is not working and I dunno why.
This one works fine!
new DatabaseConnector(true).execute("http://web2page.ch/apps/FruityNumber/highscoreShow.php");
But this one not!
new DatabaseConnector(false).execute("http://web2page.ch/apps/FruityNumber/highscoreUpload.php?user=test7&highscore=timer7");
But if I remove "if" in the class it works fine... Does someone understand why?
public DatabaseConnector(Boolean download) {
this.download = download;
}
#Override
protected Long doInBackground(String... params) {
try {
try {
//Verbinden
url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
if (download) {
//Falls die App nochmal geladen wird, sind die Daten nur einmal enthalten. Darum leeren.
arrayList.clear();
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
arrayList.add(line);
}
} else {
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
See comments in code
new DatabaseConnector(false) means
public DatabaseConnector(Boolean download) {
this.download = false; // see here
}
so
if (download) { // this won't execute because download == false
and
else {
// there is nothing here to do!
}
I'm not sure how you expect anything different..
To solve this will depend on why you are even using the boolean variable. If there is no reason for it then remove that and don't pass it anything.
Otherwise, it sounds like you want to put the upload code in the else{}
This question already has answers here:
AsyncTask Android example
(21 answers)
Closed 9 years ago.
Im making an android program that parses JSON texts from a source code of a webpage in the internet. It is working in android 2.2 but I need it now to be on android 3.0, which needs to be on the AsyncTask. I have a background about AsyncTask but I'm so confused where to put this and that. Thanks in advance everyone :)
Here is my method in the MainActivity class:
private void jsonStuffs() {
//JSON PARSER & HOME PAGE TEXTVIEWS
client = new DefaultHttpClient();
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
String jsonStr = test.getInternetData(); //go to GetMethodEx
JSONObject obj = new JSONObject(jsonStr);
//////////////////////find temperature in the JSON in the webpage
String temperature = obj.getString("temperature");
TextView tvTemp = (TextView)findViewById(R.id.textView);
tvTemp.setText(temperature);
}
//catch (JSONException e) {
// e.printStackTrace();
//}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The GetMethodEx class is this (this will find the link of the webpage then convert it's source code to text format):
public class GetMethodEx extends Activity {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
//
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://nhjkv.comuf.com/json_only.php");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally {
if (in !=null){
try{
in.close();
return data;
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}
You can do something like this (this code is just for illustration, change it as needed)
class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
protected void onPreExecute() {
// You can set your activity to show busy indicator
//setProgressBarIndeterminateVisibility(true);
}
protected JSONObject doInBackground(String... args) {
return jsonStuffs();
}
protected void onPostExecute(final JSONObject jsonObj) {
String temperature = jsonObj.getString("temperature");
TextView tvTemp = (TextView)findViewById(R.id.textView);
tvTemp.setText(temperature);
// Stop busy indicator
//setProgressBarIndeterminateVisibility(false);
}
To call this task use new MyAsyncTask().execute(); (you can pass String parameters to execute if needed)
You can change your jsonStuffs() to return JSONObject
e.g.
private JSONObject jsonStuffs() {
// ...
String jsonStr = test.getInternetData(); //go to GetMethodEx
return new JSONObject(jsonStr);
// ...
}
It is working in android 2.2 but I need it now to be on android 3.0,
which needs to be on the AsyncTask.
=> Yes it gives NetworkOnMainThreadException in 3.0 if you make web call without implementing inside Thread such as AsyncTask.
I have a background about AsyncTask but I'm so confused where to put
this and that.
=> Simply include web call logic inside doInBackground() method of the AsyncTask, in your case call getInternetData() inside doInBackground().
FYI, you can't update UI straight way while doing long running task inside the doInBackground(). Yes if you want to update UI then do follow any of the below:
Update UI from the onPostExecute() method.
or implement runOnUiThread() inside the doInBackround()
I'm writing an Android app which receives data from a server. Theoretical there could not be an internet connection so I try to catch this case by catching a SocketTimeoutException to show an error message an a retry screen or something else. Unfortunately this exception won't be thrown. At least it doesn't jump into the catch clause. What am I doing wrong?
public class HttpConnector {
private String urlString;
private int connectionTimeout = 5000; //milliseconds
public HttpConnector(String urlString) {
this.urlString = urlString;
}
public String receiveData() throws PolizeiwarnungException {
URL url = null;
HttpURLConnection urlConnection = null;
StringBuffer b = new StringBuffer();
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(connectionTimeout);
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); //Here it gets stuck if there is no connection to the server
String str;
while ((str = reader.readLine()) != null) {
b.append(str + "\n");
}
}
catch (SocketTimeoutException e) {
//TODO
e.printStackTrace();
}
catch (IOException e) {
throw new PolizeiwarnungException(e);
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return b.toString();
}
public void sendData(String data) {
//TODO
}
}
You need to also set the connect timeout. Please see this documentation.
Since the end point does not exist, without having set a connect time out the connection will never time out.
setConnectTimeout(int timeout) Sets the timeout value in milliseconds
for establishing the connection to the resource pointed by
this URLConnection instance.
I am trying to read a text file from my localhost (WAMP), but getting nothing back.
Could someone point out what I am doing wrong please.
This is how I am trying to achieve it.
try {
URL url = new URL("http://10.0.2.2/text.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((str = in.readLine()) != null) {
tv.append(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) { }
It works with a true URL, but not whenever I use localhost. I have tried using localhost and 127.0.0.1 in URL too.
i have code for hitting url but it hit only once when i run the progrm i want it hit automaticly in every 5 min. for checking the status how to do it....actually i am new in android and java so pls explain with example...v.v. thanks in advance.....
public class Activity2
{
public static String getData() {
String data = null;
try {
URL url = new URL("http://qrrency.com/mobile/j2me/cab/CabRequestStatus.php?requestid=666");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
int m=0;
StringBuffer buffer=new StringBuffer();
String str1 = " ";
while ((m=in.read())!=-1)
{
buffer.append((char)m);
str1=str1+(char)m;
cabbookingapplication.resp =str1;
data=cabbookingapplication.resp;
}
in.close();
} catch (MalformedURLException e)
{
} catch (IOException e)
{
}
return data;
you have to use the timer after every 5 min it will hit the Url which u want & will do what u want.