What would be the best way to make this run Async - java

I have to java classes, one the activity and the other is the class i want to run a void from.
Web.java looks like:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Web {
public Document requestPage(String urll) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urll);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
Document doc = Jsoup.parse(result.toString());
return doc;
}
}
And my MainActivity.java looks like this:
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class MainActivity extends AppCompatActivity {
Button Visit;
EditText Urlbox;
Web web = new Web();
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Visit = (Button)findViewById(R.id.Button);
Urlbox = (EditText)findViewById(R.id.EditText);
Visit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Document lol = web.requestPage(Urlbox.getText().toString());
if(lol.text().toString() != null){
Toast.makeText(MainActivity.this, "Visit success!",Toast.LENGTH_SHORT).show();
}
}
});
}
}
And this works fine over the main thread most, but i want to make it go over a different thread so my UI doesnt get jammed if the connection is bad
How would i make this work in async? This is my first time i use async but i just dont understand how i should use it, ive spent a few days trying to figure it out with absolutely no success
So if i could get some examples that do work that would be fantastic so i could compare it to my current code and learn what i did wrong

i handle sitution like with callback Pattern its the best option for Asynchronous networking or you can use AsyncTask but im explain cllback pattern so lets make it happen
first create callback interface
public interface Request {
void onSuccess(Document doc);
}
2 - implements Runnable for running Asynchronous request on another thread
public class Web implements Runnable {
public final Request request;
private final String urll;
Web(String urll, Request request){
this.urll = urll;
this.request = request;
}
#Override public void run() {
try{
StringBuilder result = new StringBuilder();
URL url = new URL(urll);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
Document doc = Jsoup.parse(result.toString());
// fill the cllback with result
this.request.onSuccess(doc);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// return doc;
}
}
3 - now we work with ExecutorService(ThreadPools created for reason .. its off topic here), simple thing in here we use new Thread(Runnable) before that letsimplement the calback
public class MainActivity extends AppCompatActivity implement Request{
Button Visit;
EditText Urlbox;
private Document lol;
//Web web = new Web();
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Visit = (Button)findViewById(R.id.Button);
Urlbox = (EditText)findViewById(R.id.EditText);
Visit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Document lol = web.requestPage(Urlbox.getText().toString());
String url = Urlbox.getText().toString();
Thread thread = new Thread(new Web(url, this));
thread.start();
if(lol.text().toString() != null){
Toast.makeText(MainActivity.this, "Visit success!",Toast.LENGTH_SHORT).show();
}
thread.interrupt();
}
});
}
#Override
public void onSuccess(Document doc) {
lol = doc;
}
}
and every where you need new result or request you have to create thread and if you wanna share result betwwen classes or thread this is another thing
this pattern works perfectly me.

Related

How to add parameter to Url in HttpURLConnection

I'm trying to pass the matchday to the URL for the Http connection. I know I can't get a value from the EditText in the doInBackground method so I thought to get the value in the onPreExecute method. Of I then add the variable to the URL, the program doesn't recognise the String. I saw on StackOverflow you need to add the parameters in the execute method but I don't really have got that part of the explanation.
Does anyone have an idea how to add the matchday to the URL, entered in the EditText matchdayText?
Thanks in advance!
Rob Nickmans
CODE:
package ga.rndevelopment.footballpronostics;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText matchdayText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "HIDDEN";
static final String API_URL = "http://api.football-data.org/v2/competitions/PL/matches/?matchday=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = findViewById(R.id.responseView);
matchdayText = findViewById(R.id.matchdayText);
progressBar = findViewById(R.id.progressBar);
Button queryButton = findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new FetchData().execute();
}
});
}
class FetchData extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
String matchDay = matchdayText.getText().toString();
String apiUrl = API_URL + matchDay;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("X-Auth-Token", API_KEY);
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
#Override
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
}
First Create the connection using URL Connection.There by create
buffer writer and pass the all requested data in one single String
buffer variable there by it will take to concern URL and along with
Requested parameter and its values. Please go Through this Below
sample Example
URL url = new URL("give your URL ");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
final StringBuilder reqstData = new StringBuilder(100);
reqstData.append("&userId=").append(userId);
reqstData.append("&roleId=").append(roleId);
reqstData.append("&userName=").append(userName);
out.write(reqstData);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

App Downloading web page not working

I am learning android development and in a tutorial i am following demonstrated how to download a web page and print it into logs with AsyncTask class but the problem is, app is hanging ( ui elements not appearing neither in emulator nor in my phone ) and when the ui elements appear ( after a long time say 5 minutes) the html source in log is not showing
here is the code
package com.example.slimshady.downloadhtml;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... buttoks) {
URL url;
HttpURLConnection httpURLConnection = null;
String result = "";
// try catch for if malformed url
try {
url = new URL(buttoks[0]);
httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1)
{
char current = (char)data;
result+=current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask downloadTask = new DownloadTask();
try {
String content = downloadTask.execute("https://www.google.com").get();
Log.i("returned STring", content.toString());
}catch (Exception e)
{
e.printStackTrace();
}
}
}
everything seems ok but still no html source logging and what can be the cause for the ui elements appearing alot later than they should ? i mean the whole reason for an AsyncTask is that they run independent of the main thread so the ui elements are not effected by the task am i right ?
The issue is , you are invoking get which will block your thread until you get the response so simply use
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadTask().downloadTask.execute("https://www.google.com");
}
and update UI in onPostExecute
You can also improve the code using StringBuffer and BufferReader as
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... buttoks) {
URL url;
HttpURLConnection httpURLConnection = null;
String result = "";
StringBuffer buf = new StringBuffer();
// try catch for if malformed url
try {
url = new URL(buttoks[0]);
httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream in = httpURLConnection.getInputStream();
BufferedReader reader =new BufferedReader(new InputStreamReader(in));
if (is != null) {
while ((result = reader.readLine()) != null) {
buf.append(result);
}
}
return buf.toString();
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
}
#Override
... onPostExecute(String str){
// update UI here
}
}

android app urlconnection get request wont work

I am having a problem.
I can't figure out why the following code won't work.
It's a simple app that sends a GET request to some php fragment that supposed to insert a row in a table.
I can't understand why it doesn't work.
Please help.
java:
package com.example.michael.biyum;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
final AlertDialog alertDialog = alertDialogBuilder.create();
Button startBtn = (Button) findViewById(R.id.btn);
final TextView t = (TextView) findViewById(R.id.hello);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.chatty.co.il/biyum.php?q=mkyong");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
Toast.makeText(getApplicationContext(),"GET:"+current,Toast.LENGTH_LONG).show();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
});
}
}
php:
<?php
require('connect.inc.php');
$update_offline="INSERT INTO offline_waiters (user_partner,mail,chat_room) VALUES(0,'gavno','gavno')";
$query_run= mysqli_query($conn,$update_offline);
echo "new";
?>
It's a simple test that should enter a new row in my table.
When I make the request manualy via a browser it works fine.
Once again please help me understand where is the problem.
You need to get the network operation off of the main thread.
I just got this working and tested using an AsyncTask:
class MyAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
StringBuilder result = new StringBuilder();
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.chatty.co.il/biyum.php?q=mkyong");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
result.append(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),"GET:"+result,Toast.LENGTH_LONG).show();
}
}
Just execute the AsyncTask from your click listener:
startBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
new MyAsyncTask().execute();
});
Result in the Toast:

Setting text to multiple TextFields with Asynctasks crashes app

What I want to achieve is the following:
In my view, I have 4 TextViews that should show the amount of items in the connected databases. This is done using a simple php script.
The problem I have is that I get all the correct values from the database, but when I try to set those values to my TextViews, the app crashes.
I have tried to look if using to many Asynctasks could be a problem, but when I decide to comment out the only line inside the SetTextForTextView() function, it all works like a charm and all the expected values are printed to my log. So with that being said, I dont think using multiple Asynctasks at the same time is the problem here, but I have really no idea what is.
Something that might be worth mentioning is when I comment out the following bit like this, the app doesn't crash...
shoesAmount = (TextView) findViewById(R.id.menuTvShoesAmount);
DatabaseTask taskA = new DatabaseTask(shoesAmount);
taskA.execute("getAmount", "shoes");
// tshirtsAmounts = (TextView) findViewById(R.id.menuTvTshirtsAmount);
// DatabaseTask taskB = new DatabaseTask(tshirtsAmounts);
// taskB.execute("getAmount", "tshirts");
//
// jeansAmount = (TextView) findViewById(R.id.menuTvJeansAmount);
// DatabaseTask taskC = new DatabaseTask(jeansAmount);
// taskC.execute("getAmount", "jeans");
//
// blousesAmount = (TextView) findViewById(R.id.menuTvBlousesAmount);
// DatabaseTask taskD = new DatabaseTask(blousesAmount);
// taskD.execute("getAmount", "blouses");
But then again with any other combination for example like this one, and the app crashes again...
// shoesAmount = (TextView) findViewById(R.id.menuTvShoesAmount);
// DatabaseTask taskA = new DatabaseTask(shoesAmount);
// taskA.execute("getAmount", "shoes");
//
tshirtsAmounts = (TextView) findViewById(R.id.menuTvTshirtsAmount);
DatabaseTask taskB = new DatabaseTask(tshirtsAmounts);
taskB.execute("getAmount", "tshirts");
//
// jeansAmount = (TextView) findViewById(R.id.menuTvJeansAmount);
// DatabaseTask taskC = new DatabaseTask(jeansAmount);
// taskC.execute("getAmount", "jeans");
//
// blousesAmount = (TextView) findViewById(R.id.menuTvBlousesAmount);
// DatabaseTask taskD = new DatabaseTask(blousesAmount);
// taskD.execute("getAmount", "blouses");
Does anyone can point me out into the direction where I might be going wrong?
Thanks!
(here is the full code)
package ishopper.theindiestudio.com.appname;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
public class Menu extends AppCompatActivity {
private ImageButton btnHelp, btnAccount, newest1, newest2, newest3;
private TextView shoesAmount, tshirtsAmounts, jeansAmount, blousesAmount;
private Button browseShoes, browseTshirts, browseJeans, browseBlouses;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
context = this;
btnHelp = (ImageButton) findViewById(R.id.menuBtnHelp);
btnAccount = (ImageButton) findViewById(R.id.menuBtnAccount);
btnAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAccountOptions();
}
});
btnHelp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onHelp();
}
});
newest1 = (ImageButton) findViewById(R.id.menuIbNewest1);
newest2 = (ImageButton) findViewById(R.id.menuIbNewest2);
newest3 = (ImageButton) findViewById(R.id.menuIbNewest3);
//set newest items
shoesAmount = (TextView) findViewById(R.id.menuTvShoesAmount);
DatabaseTask taskA = new DatabaseTask(shoesAmount);
taskA.execute("getAmount", "shoes");
tshirtsAmounts = (TextView) findViewById(R.id.menuTvTshirtsAmount);
DatabaseTask taskB = new DatabaseTask(tshirtsAmounts);
taskB.execute("getAmount", "tshirts");
jeansAmount = (TextView) findViewById(R.id.menuTvJeansAmount);
DatabaseTask taskC = new DatabaseTask(jeansAmount);
taskC.execute("getAmount", "jeans");
blousesAmount = (TextView) findViewById(R.id.menuTvBlousesAmount);
DatabaseTask taskD = new DatabaseTask(blousesAmount);
taskD.execute("getAmount", "blouses");
}
public void SetTextForTextView(TextView textview, String result){
textview.setText(result);
}
public void onAccountOptions () {
Intent i = new Intent(this, AccountDetailsActivity.class);
startActivity(i);
}
public void onHelp () {
}
public void onBackPressed() {
//disabled back button
}
private class DatabaseTask extends AsyncTask<String, Void, String> {
private String taskType;
private String productType;
private TextView textView;
private ImageButton imageButton;
DatabaseTask (TextView mTextView){textView = mTextView;}
#Override
protected String doInBackground(String... params) {
String task = params[0];
if (task.equals("getAmount")) {
Log.e("doInBg", "getAmount");
String login_url = "http://url.eu/directory/script.php";
String tProductType = params[1];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String postData = URLEncoder.encode("producttable", "UTF-8") + "=" + URLEncoder.encode(tProductType, "UTF-8");
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
Log.e("doInBgResult", result.toString());
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Menu activity = (Menu) context;
activity.SetTextForTextView(textView, result.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
}
The AsyncTask's doInBackground() runs in another thread and you can't change the UI from another thread, Only the main one. I suggest you do the same job in onPostExecute() after you finish your long job. Return the String result you want to use to the main thread
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
// no need for that
//Menu activity = (Menu) context;
//activity.SetTextForTextView(textView, result.toString());
reutrn result;
then update the text
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
SetTextForTextView(textView, result);
}
}
I suggest reading more about it from here and here

Cannot get GET request working for Android

I am trying to make a simple GET request to my local NodeJS server to get some JSON objects. I changed the request so it happens as an AsyncTask rather than in the UI thread. But I am still not able to get it to work. Does this code look correct? Sorry, not great with Java yet.
package com.dd.relay;
import com.dd.relay.HttpRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public final static String EXTRA_MESSAGE = "com.dd.relay.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We'll define a custom screen layout here (the one shown above), but
// typically, you could just use the standard ListActivity layout.
setContentView(R.layout.activity_main);
// Make a GET request for data
String url = "http://localhost.com/contacts";
String res = null;
try {
HttpRequest request = new HttpRequest();
request.execute(new URL(url));
Log.v(EXTRA_MESSAGE, res);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textv);
Context context = this.getApplicationContext();
Toast mytoast = Toast.makeText(context, res, Toast.LENGTH_LONG);
mytoast.show();
textView.setText(res);
// Create list for contacts
/* List<Map<String, RelayContact>> data = null;
// Now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleAdapter(this, data, 0, new String[] {"First", "Number"}, new int[] {android.R.id.text1, android.R.id.text2}); // Parallel array of which template objects to bind to those columns.
// Bind to our new adapter.
this.setListAdapter(adapter);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And here is my custom HttpRequest AsyncTask class
package com.dd.relay;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
public class HttpRequest extends AsyncTask<URL, Void, Void> {
protected String doInBackground(URL url) throws Exception {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
protected void onProgressUpdate(Integer progress) {
}
protected void onPostExecute(String result) {
System.out.println(result);
}
#Override
protected Void doInBackground(URL... arg0) {
// TODO Auto-generated method stub
return null;
}
}
Android does not allow network communication to be done on the UI thread. Android provides a class called AsyncTask that is intended for such interactions. See this link for details and one option for a solution (This is probably what you want):
How to fix android.os.NetworkOnMainThreadException?
or you can also create a custom class that extends Thread or implements Runnable that posts to the UI thread using a Handler
try this link hope use full to you :-
Verifying login details via http get : Android
public class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// call function
login(userName, password);
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}

Categories

Resources