I have cleaned and rebuild my code as well but still the issue is not solved.
Below is the code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result = null;
String stringUrl = "https://www.ecowebhosting.co.uk/";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(stringUrl);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urls[0]);
//It is like opening a browser
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char currentChar = (char) data;
result = result + currentChar;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Results",s);
}
}
}
The code is running fine but nothing is printed in the logs. The following is the log:
AsyncTask is an asynchronous process. So when you call Log.i("Result:", result);, the AsyncTask is not finished and result is still empty.
You should print your result from onPostExecute() method.
You can look on this page.
Here is some examples on how to implement an AsyncTask correctly:
https://www.upwork.com/hiring/mobile/why-you-should-use-asynctask-in-android-development/
How to use AsyncTask correctly in Android
Best
You only have to change code inside your doInBackGround
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result;
String inputLine;
try {
URL myUrl = new URL(urls[0]);
HttpURLConnection connection =(HttpURLConnection)
myUrl.openConnection();
connection.setReadTimeout(150000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("GET");
connection.connect();
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Results",s);
}
}
Related
Using AsyncTask freezes my whole app. i have an icon that rotates while the Http action is happening in the background. but the app just freezes till it finishes that action. Is there an alternative?
The below class sends the JSON to the server, the server has multiple endpoints and stuff like that. now when calling class calls the execute() method, the app freezes until the task is complete.
public class Connector extends AsyncTask<String, Void, Void> {
private String ip = "http://192.168.1.127";
private String port = "5000";
private URL Url;
private JSONObject jsonObject;
private String method = "";
private StringBuilder output = new StringBuilder();
Connector(String url, JSONObject jsonObject, String method)
{
try {
this.method = method;
this.Url = new URL(ip+":"+port+url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
this.jsonObject = jsonObject;
//Connect to URL
}
#Override
protected Void doInBackground(String... strings) {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) Url.openConnection();
Log.i("Data", "Data sent => " + jsonObject.toString());
try {
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod(method);
httpURLConnection.setRequestProperty("content-type", "application/json");
httpURLConnection.connect();
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
if(jsonObject != null)
{
outputStream.writeBytes(jsonObject.toString());
outputStream.flush();
outputStream.close();
}
InputStreamReader inputStreamReader = new InputStreamReader((InputStream) httpURLConnection.getContent(), Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while(line != null)
{
output.append(line);
line = reader.readLine();
}
}finally {
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
String getMessge() {
Log.i("Data", "Data received <= " + output.toString());
return output.toString();
}
}
Please use Retrofit library.
You can find samples to use Retrofit easily.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
This is one of them.
Hope it to help you. Thanks.
I have 3 url's of pages which content has a json structure. I must read a page from an url in an async task.
How can I read the 3 urls sequentially, so that I can work with the 3 json's maintaining their order?
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]); //params[0] = my first url
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");
}
return buffer.toString();
//read also the second and the third url
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
#Override
protected void onPostExecute(String result) {
// ... do something with the first json
// ... do something with the second json
// ... do something with the third json
}
}
Just move the logic for mapping one URL to JSON out into a method, and call it for each argument you pass in. Then, modify your AsyncTask so it outputs List<String> and not String from doInBackground().
protected List<String> doInBackground(String... params) {
final List<String> out = new ArrayList<>(paramas.length);
for(String url : params) {
out.add(downloadJson(url));
}
return out;
}
#Override
protected void onPostExecute(List<String> results) {
//A list of your JSON results...
}
private String downloadJson(String url) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "{}"; //Default to an empty JSON object
}
I want to use AsyncTask to connect with the server but I got error ondoInBackground. The error required that java.lang.string so how can I improve the code in Update()? How to insert "Return" in Update() method?
public void Update(final String urlString){
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write("name=abc");
writer.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
stringBuilder .append(line);
}
String result = stringBuilder .toString();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public class MyAsyncTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String...url) {
return Update(url[0]);
}
#Override
protected void onPostExecute(String result){
Log.d("TAG", result);
}
}
How to use AsyncTask with urlconnection which requird to insert return
You need to return a string in your Update() method
Also no need to use another Thread in your Update() method because AsyncTask already runs in the background
SAMPLE CODE
public String Update(final String urlString){
String result="";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write("name=abc");
writer.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
stringBuilder .append(line);
}
result = stringBuilder .toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public class MyAsyncTask extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String...url) {
return Update(url[0]);
}
#Override
protected void onPostExecute(String result){
Log.d("TAG", result);
}
}
Use the below code to start AsyncTask:
MyAsyncTask task = new MyAsyncTask();
task.execute(URL);
Note that: Using AsyncTask you should not create a new Thread in the Update(URL) method
extends AsyncTask<String,Void,String>
Here String means that AsynkTask waits for a String type in Return.
protected String doInBackground(String...url) {
return Update(url[0]);
}
Already in a separate thread. Just delete it from a method.
ps. Don't use AsynkTask for connections with the server. (it's an unstable thing with Activity lifecycle )
Please help me it should call again the server if the response code is 204 how to call?
String command = ("http://api.railwayapi.com/live/train/" + m_train_Number + "/doj/" + m_year + m_month + m_day + "/apikey/tc9sc898/");
new JSONTask().execute(command);
public class JSONTask extends AsyncTask<String, String, LiveStationModel>
{
LiveStationModel liveStationModel = null;
protected LiveStationModel doInBackground(String... params) {
IOException e;
MalformedURLException e2;
List<LiveStationModel> myList = null;
Throwable th;
JSONException e3;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) new URL(params[0]).openConnection();
connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
try {
StringBuffer buffer = new StringBuffer();
String str = "";
while (true) {
str = bufferedReader.readLine();
if (str == null) {
break;
}
buffer.append(str);
}
your can check that it onPostExecute method like:
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//check your if condition here
}
public class JSONTask extends AsyncTask<String, String, LiveStationModel>
{
int resp;
-------
connection.connect();
resp = connection.getResponseCode();
--------
}
Now override onPostExecute like this,
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(resp == 204)
{
new JSONTask().execute(command);
}
else
{
//your code here
}
}
Use the if condition in onPostExecute method of AsyncTask.
in your onPostExecute method check you are getting expected result or not, if not than again call your new JSONTask().execute(command);
like
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
new JSONTask().execute(command);
}
This will check if the response is 204 or not but if you want to try another connection, disconnect current one and then make another connection with different url; because if you repeat your URL, you get the same results again and again(NO_CONTENT).
public class JSONTask extends AsyncTask<String, String, LiveStationModel>
{
LiveStationModel liveStationModel = null;
protected LiveStationModel doInBackground(String... params) {
IOException e;
MalformedURLException e2;
List<LiveStationModel> myList = null;
Throwable th;
JSONException e3;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) new URL(params[0]).openConnection();
connection.connect();
if(connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT)
{
//do what you gonna do
}
if you want to repeat until you get the content
use a loop like this:
try {
int code = connection.getResponseCode();
while(code == 204)
{
connection = (HttpURLConnection) new URL(params[?]).openConnection(); // Different Parameter here
connection.connect();
....
}
I'm implementing JSP page in my Android application. I don't know how to use JSP Url in Android. I tried and run the application. But the page is blank does not show any info in Android layout and also in log cat. Here is my code.
public class JSP_Activity extends Activity
{
public static String strUrl=null;
String strText = null;
public void OnCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.jsp_page);
connectWithGet_JspPage();
}
private void connectWithGet_JspPage()
{
class GetJspPage extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... strUrls)
{
// TODO Auto-generated method stub
strUrl="http://test.window2india.com/mobile/home.jsp";
Log.e("strUrl :=","" + strUrl);
String strOutPut = null;
strOutPut=getOutPutFromUrl(strUrl);
Log.e("strOutPut :="," "+strOutPut);
return strOutPut.toString();
}
protected void onPostExecute(String output1)
{
//outputText.setText(output1);
Log.e("strOutPut :="," "+output1);
}
}
GetJspPage getJspPageAsyncTask = new GetJspPage();
getJspPageAsyncTask.execute();
}
private String getOutPutFromUrl(String url)
{
StringBuffer output = new StringBuffer("");
try
{
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
catch (IOException e1)
{
e1.printStackTrace();
}
return output.toString();
}
private InputStream getHttpConnection(String urlString)
throws IOException
{
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try
{
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
stream = httpConnection.getInputStream();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return stream;
}
}
Try this code,it will help for display the content send by the jsp.This code is useful for normal layout not for webview.You have to parse the content and display in your custom layout.
new Thread(new Runnable()
{
public void run()
{
try
{
URL url = new URL("http://test.window2india.com/mobile/home.jsp");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String x = "";
String total = "";
int i=0;
ArrayList<String> content = new ArrayList();
while((x = r.readLine()) != null)
{
content.add(x);
}
in.close();
r.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}).start();