How to parse data from multiple URLs using asyncTask - android

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) {
...
}

Related

Call Async Webservice From For Loop

When I call a webservice from a for loop to insert/update data into MySQL using PHP only the last item gets inserted/updated because (i think) the for loop completes quicker than the webservice, how can I delay my for loop or achieve a webservice call for each item returned in the for loop one after another.
For Loop Code:
for (int i = 0; i < lv.getCount(); i++) {
view = lv.getAdapter().getView(i, lv.getChildAt(i), lv);
if (view != null) {
// Getting my views
tvItem = (TextView) view.findViewById(R.id.tvItem);
strItem = tvItem.getText().toString();
//Call AsyncTask
accessWebService();
}
}
Webservice:
private class Webservice extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
}
return answer;
}
#Override
protected void onPostExecute(String result) {
try{
ld();
}catch (Exception e){
}
}
}// end async task
public void accessWebService() {
Webservice task = new Webservice();
//Update MySQL Using PHP
}
When you want to insert/update all data from for loop you must use callback like interfaces. Once you implement this it will wait for completing the process. Once completed it will call success or error method. Based on this you insert/update another record.
interface DataCallback {
fun onSuccess(result: Any)
fun onError(error: Any)
}
public void getCountries(new DataCallback(){
#Override
public void onSuccess(Object result){
// insert/update next record
}
#Override
public void onError(Object error){
// show error message
}
});
This is just example. You should convert it based on your need. Thanks.

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.

get web page content

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.

Android Programming: HTTP GET REQUEST NOT WORKING

I require a GET reequest from my own server to be extracted from the web and then displayed on screen with a TextView.
I have set up a GET Request.
public class GetMethodEx {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try
{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
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();
}
}
}
}
}
And I have set up on my main thread to extract the information and display it in a text view.
public class Home extends Activity {
TextView httpStuff;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
httpStuff = (TextView) findViewById(R.id.tvhttp);
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
However, the Textview doesnt seem to change?
Can someone help me please.
Change your code using AsyncTask if you want to make any network operation from Ui Thread as:
public class Home extends Activity {
TextView httpStuff;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
httpStuff = (TextView) findViewById(R.id.tvhttp);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returned;
}
#Override
protected void onPostExecute(String result) {
// Update Ui here
httpStuff.setText(result);
}
}
}
Android OS > = 3.0
does not allow NetworkRequest on main UI thread.
Use AsyncTask to call webrequest.

I get NetworkOnMainThreadException eaven when I make request from another thread

I understand the point of the android.os.NetworkOnMainThreadException that targets HoneyComb devices but the following code throws the same exception:
class MakeRequest extends AsyncTask<String,Integer,Void>
{
#Override
protected Void doInBackground(String... params) {
DefaultHttpClient cli = new DefaultHttpClient();
try {
String url = params[0].replace(" ", "%20");
HttpResponse resp = cli.execute(new HttpGet(url));
BufferedReader read = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
String tmp = "",rezultat = "";
setResult("");
while ((tmp = read.readLine()) != null)
{
rezultat = rezultat + tmp;
}
setResult(rezultat);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
setResult("");
return null;
}
return null;
}
//Sample call
HttpRequester cc = new HttpRequester();
MakeRequest test = cc.new MakeRequest();
test.doInBackground(url);
try this.
new MakeRequest().execute(url);

Categories

Resources