get web page content - android

I have some errors when I read a web page content on the main thread
public class WebReader extends AsyncTask<String, String, String> {
private String result;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
System.out.println(params[0]);
try {
result = client.execute(request, responseHandler);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.result = result;
return result;
}
protected void onProgressUpdate(String... progress) {
}
#Override
protected void onPostExecute(String result) {
this.result = result;
}
public String getResult(){
return result;
}
}
And I use this in :
public static void testAsync(){
String result = null;
WebReader wr = new WebReader();
wr.execute("http://www.google.fr");
result = wr.getResult();
while(result==null){
try {
Thread.sleep(1000);
result = wr.getResult();
} catch (InterruptedException e) {
result = "";
}
}
System.out.println(result);
}
I don't realy find the soltion to return a String
Thanks

I think the problem is the line
this.result = result;
in
protected void onPostExecute(String result) {
because I don't see how onPostExecute gets passed the result parameter, so you are assigning NULL. I removed the line and it worked.

Related

How to parse data from multiple URLs using asyncTask

The main problem is I'm unable to return two value help. i have tried lot of time but no success. And guys I'm new to this so please write your answer with respect to my code thanks in advance.
Here's my code
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
uss = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INRUSD%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject usjObj;
usjObj = new JSONObject(uss);
usResult = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
eurr = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INREUR%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject eurjObj;
eurjObj = new JSONObject(eurr);
eurResult = eurjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return eurResult + usResult;
////PROBLEM IS HERE ACTUALLY I DON'T KNOW HOW TO RETURN TWO OR MORE VALUE/////"
}
#Override
protected void onPostExecute(String usResult) {
valueus = Double.parseDouble(usResult);
inputus = lengthvalue * valueus;
us.setText("" + inputus);
valueeur = Double.parseDouble(eurResult);
inputeur = lengthvalue * valueeur;
eur.setText("" + inputeur);
}
}
public String getJson(String url) throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
}
You should not try to cram everything into a String. There are better data structures to hold multiple values: array, Vector, List, etc. Declare your AsyntTask as:
public class calculate extends AsyncTask<String, String, String[]>
and then your doInBackgorund method would be something like this:
#Override
protected String doInBackground(String... params) {
String[] result = new String[numResults];
...
result[0] = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
...
result[1] = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
...
return result;
}
And finally your onPostExecute would be
#Override
protected void onPostExecute(String[] usResult) {
...
}

Asynctask android return contents "doinBackground

I would like to retrieve the contents of my variable "$content" in my activity.
But I don't know how to use the return value of my doinbackground.
Can you help me ?
thank you in advance
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
RestOperation test = new RestOperation();
test.execute(restURL);
}
private class RestOperation extends AsyncTask<String, Void, String> {
//final HttpClient httpClient = new DefaultHttpClient();
String content;
String error;
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView serverDataReceived = (TextView)findViewById(R.id.serverDataReceived);
TextView showParsedJSON = (TextView) findViewById(R.id.showParsedJSON);
// EditText userinput = (EditText) findViewById(R.id.userinput);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle("Please wait ...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
URL url;
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
content = sb.toString();
} catch (MalformedURLException e) {
error = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
error = e.getMessage();
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(error!=null) {
serverDataReceived.setText("Error " + error);
} else {
serverDataReceived.setText(content);
String output = "";
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(content);
JSONArray jsonArray = jsonResponse.names();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject child = jsonArray.getJSONObject(i);
String name = child.getString("name");
String number = child.getString("number");
String time = child.getString("date_added");
output = "Name = " + name + System.getProperty("line.separator") + number + System.getProperty("line.separator") + time;
output += System.getProperty("line.separator");
Log.i("content",content);
}
showParsedJSON.setVisibility(View.INVISIBLE);
showParsedJSON.setText(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
You can directly call to the method which exist in activity, from onPostExecute method of asynctask by passing "content" value.
#Override
protected void onPostExecute(String content) {
Activity.yourMethod(content);
}
If you want to return the value from asynctask you can use
content = test.execute(url).get();
but it is not a good practice of asynctask, because it is working as serial execution. So it is not fulfill the use of asynctask for palatalization.Because get() will block the UI thread.

Android Null pointer exception while using Async Task method [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
While executing Async Task in android and getting Json response and while converting response into JSONArray,i am getting NUll pointer Exception.
I am trying fron two days Please help me.
Here is the code to get the Json String.
error is at task.get().
DownloadTask task=new DownloadTask();
task.execute(new String[]{"URL"});
try {
jsonArr=new JSONArray(task.get());
Toast.makeText(getApplicationContext(), jsonArr.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < jsonArr.length(); i++) {
obj = jsonArr.getJSONObject(i);
name = obj.getString("name");
phno = obj.getString("phone");
dcount = obj.getString("count");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Here Is the Async task code.
class DownloadTask extends AsyncTask<String,Void,String>{
private ProgressDialog mProgressDialog=new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute(){
mProgressDialog.setMessage("Processing");
mProgressDialog.show();
}
#Override
protected String doInBackground(String... targetURL) {
URL url;
HttpURLConnection connection = null;
try {
url = new URL(targetURL[0]);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
/* //Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes("BID1");
wr.flush();
wr.close();*/
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT);
mProgressDialog.dismiss();
}
}
You are forgot to call the super method of the onPostExecute
It should be like this
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT);
mProgressDialog.dismiss();
super.onPostExecute(result);
}
Other Solution
You can use an interface for your callback
ICallback.java
public interface ICallback {
void onResult(String result);
}
DownloadTask
class DownloadTask extends AsyncTask<String, Void, String> {
private ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);
private ICallback callback;
public DownloadTask(ICallback callback) {
this.callback = callback;
}
#Override
protected void onPreExecute() {
//Your Codes Here
}
#Override
protected String doInBackground(String... targetURL) {
//Your Codes Here
}
#Override
protected void onPostExecute(String result) {
//Your Codes Here
callback.onResult(result)
}
}
How to use it
DownloadTask task = new DownloadTask(new ICallback() {
#Override
public void onResult(String result) {
try {
jsonArr=new JSONArray(result);
Toast.makeText(getApplicationContext(), jsonArr.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < jsonArr.length(); i++) {
obj = jsonArr.getJSONObject(i);
name = obj.getString("name");
phno = obj.getString("phone");
dcount = obj.getString("count");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
task.execute(new String[]{"URL"});

d How can I use progress bar while fetching data from database?

I'm really bad at googling things I want so I decided to ask here. My question is is it possible to show a progress bar while fetching the data from the database? I'm using the typical code when fetching data(Pass value to php and the php will do the query and pass it again to android)
Edit(I have tried adding proggressdialog but the problem now is the loaded data will appear first before the progress dialog here's my AsyncTask code)
public class getClass extends AsyncTask<String, Void, String> {
public getClass()
{
pDialog = new ProgressDialog(getActivity());
}
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}
Have you tried using an AsyncTask?
You can show your progress bar on the preExecute method and then hide it on postExecute. You can do your querying inside the doInBackground method.
In addition to what #torque203 pointed, I would suggest you to check
http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)
this method was created for that purpose, showing progress to the user.
From developers docs:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
#Override
protected void onPreExecute() {
//show progress bar here
}
protected Long doInBackground(URL... urls) {
//Pass value to PHP here
//get values from your PHP
}
protected void onPostExecute(Long result) {
//Here you are ready with your PHP value. Dismiss progress bar here.
}
}
public void onPreExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void doInBackground() {
//do your JSON Coding
}
public void onPostExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
public class getClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}

AsyncTask and Telnet doesn't show ProgressDialog

I am using an asynctask while I am doing some telnet operations. However, the progressdialog is not shown, and I am almost 100% sure that Telnet is the cause.
Please take a look to my code and help me to find where is the problem.
Thanks
public class TelnetManager extends AsyncTask<String, Void, String>{
private TelnetClient telnet;
private int port;
private String IP;
private ProgressDialog dialog;
private Context context;
public TelnetManager(Context c,String IP, int port, String user, String pass)
{
context=c;
this.IP=IP;
this.port=port;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(context);
dialog.setMessage(context.getResources().getString(R.string.msg_wait));
dialog.show();
}
public String readString() throws IOException
{
InputStream in = new BufferedInputStream(telnet.getInputStream());
int read=0;
String s=null;
do
{
byte[] buffer = new byte[1024];
read = in.read(buffer);
if(read > 0)
{
if(s==null)s=new String(buffer, 0, read);
else s+=new String(buffer, 0, read);
Log.e("S",s);
}
}
while (read > 0);
in.close();
return s;
}
public void writeString(String command) throws IOException
{
OutputStream out = telnet.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out,"UTF-8");
writer.write(command+'\n');
writer.flush();
}
#Override
protected String doInBackground(String... params) {
telnet = new TelnetClient();
String s="";
try {
telnet.setConnectTimeout(10000);
telnet.connect(IP,port);
telnet.setKeepAlive(true);
writeString("password");
writeString(params[0]);
writeString("exit");
String aux=readString();
telnet.getInputStream().close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
telnet.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(dialog!=null && dialog.isShowing())
{
dialog.dismiss();
}
}
}
And here is where I call the AsyncTask:
String list=null;
try {
list=new TelnetManager(this,"192.168.11.30", 10010, null, null).execute("son").get();
construirLayout(list,R.id.containerON);
list=new TelnetManager(this,"192.168.11.30", 10010, null, null).execute("soff").get();
construirLayout(list,R.id.containerOFF);
}
catch (InterruptedException e) {
Toast.makeText(this,"InterruptedException",3000).show();
e.printStackTrace();
}
catch (ExecutionException e) {
Toast.makeText(this,"ExecutionException",3000).show();
e.printStackTrace();
}
If you call get() on an AsyncTask, you're telling the UI thread to block and wait for the AsyncTask results. Since the UI thread is blocked, it cannot show the ProgressDialog.
You should instead provide a callback to the AsyncTask, to be fired in onPostExecute().

Categories

Resources