How can I use a variable outside the onPostExecute method? - java

I have a MySQL database on a webserver and I read the data from this database in my application, but after I read the variables I can't use the "volt" variable outside the onPostExecute. I try t use adapter, but i can't use the data in the adapter like a intiger variable, just i can add to listview. So far i Don't find a solution for my problam.
I hope you can help me.
package com.example.wifis;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
// int tomb []={};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.list_item);
adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
new Conection().execute();
}
class Conection extends AsyncTask<String, String, String>{
#Override
public String doInBackground(String... strings) {
String result="";
String host="http://localhost/store/cars.php";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader= new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer= new StringBuffer("");
String line = "";
while ((line = reader.readLine()) !=null ){
stringBuffer.append(line);
break;
}
reader.close();
result = stringBuffer.toString();
}
catch (Exception e){
return new String("There exeption: "+ e.getMessage());
}
return result;
}
#Override
public void onPostExecute(String result){
// Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if(success==1){
JSONArray cars = jsonResult.getJSONArray("cars");
JSONObject car = cars.getJSONObject(0);
int id = car.getInt("id");
int volt = car.getInt("szam");
String line = id + "-" + volt;
adapter.add(line);
// tomb[0]=szam;
}else{
Toast.makeText(getApplicationContext(), "NOT OK ", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

As I have tried to explain in my post here
the values you're trying to access aren't synchronous, meaning that your code does not execute top down. The AsyncTask returns a value at some point. we don't know when that will be, but when it returns the value, you'll have access to it within onPostExecute. this means that you can make use of the values as they are received there and only there, as that is the only place where you'll actually receive those values.
to get this value returned to your main activity, you can do something like this :
create an interface
public interface MyCallback {
void myResult(YourResultType output); //here, i believe this will be string for your specific case
}
This interface allows us to move the value we receive to another class when it's received
Next,
Go to your AsyncTask class, and declare interface MyCallback as a variable :
public class MyAsyncTask extends AsyncTask<String, String, String> {
public MyCallback callback = null;
#Override
protected void onPostExecute(String result) {
callback.myResult(result);
}
}
#Override
protected void onPostExecute(String result) {
callback.myResult(result);
}
now for your main activity:
public class MainActivity implements MyCallback {
MyAsyncTask asyncTask = new MyAsyncTask();
#Override
public void onCreate(Bundle savedInstanceState) {
//set your listener to this class
asyncTask.callback = this;
//execute the async task
asyncTask.execute();
}
//this overrides the implemented method from asyncTask
#Override
void myResult(YourResultType output){
//Here you will receive the result returned from the async task
}
}
please also note that async tasks are deprecated
also note, my java is quite rusty, I am fortunate enough to only use kotlin these days, feel free to correct me on any mistakes :)

Related

JAVA having trouble retrieving volley result variable value in another class

I have two classes in my android Java Project:
one is API which is inside a local android Module Library that has this code
package com.example.validationchecklib;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class API extends Application{
public static int result;
public static int resultInApi;
public int checkSubscription(String packageName, String purchaseCode, RequestQueue q) {
String apiUrl = "https://package.evisions.tech/check_validation.php?package_name=" + packageName;
// creating a new variable for our request queue
//RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
// in this case the data we are getting is in the form
// of array so we are making a json array request.
// below is the line where we are making an json array
// request and then extracting data from each json object.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, apiUrl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
//creating a new Json object and getting each
//object from our json array.
try {
// we are getting each json object.
JSONObject responseObj = response.getJSONObject(i);
// now we get our response from API in json object format.
// in below line we are extracting a string with
// its key value from our json object.
// similarly we are extracting all the strings from our json object.
String apiPackage = responseObj.getString("package_name");
String apiPurchaseCode = responseObj.getString("purchase_code");
int apiStatus = responseObj.getInt("status");
if (apiStatus == 1) {
if (apiPackage.equalsIgnoreCase(packageName) && apiPurchaseCode.equalsIgnoreCase(purchaseCode)) {
//subcription status is valid and user inputed data matches with api data
result = 1;
System.out.println("Result in Api = "+result);
break;
}
} else if (apiStatus == 0) {
result = 0;
System.out.println("Result in Api = "+result);
break;
} else {
result = 2;
System.out.println("Result in Api = "+result);
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
result = 3;
System.out.println("Result in Api = Failed to get the data...");
}
});
q.add(jsonArrayRequest);
return result;
}
}
The second class is MainActivity where I want to retrieve the value from the checkSubsccription() method that is on API class but I am getting 0 even when the request from volley has value 1.
You can test the request using this URL: https://package.evisions.tech/check_validation.php?package_name=aaaa
this is the code for MainActivity
package com.example.aaaa;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.example.validationchecklib.Subscription;
import com.example.validationchecklib.API;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
//Sample implementation of the Purchase validation android Library
public String packageName, purchaseCode;
public TextView txtPackageName, txtPurchaseCode;
public Button btnResult;
int serverResponse;
public String r;
private ArrayList<Subscription> subscriptionModalArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
subscriptionModalArrayList = new ArrayList<>();
txtPackageName = findViewById(R.id.edtPackageName);
txtPurchaseCode = findViewById(R.id.edtPurchaseCode);
btnResult = findViewById(R.id.btnVerify);
RequestQueue queue = Volley.newRequestQueue(this);
API api = new API();
btnResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
packageName = txtPackageName.getText().toString().trim();
purchaseCode = txtPurchaseCode.getText().toString().trim();
serverResponse = api.checkSubscription(packageName,purchaseCode, queue);
System.out.println("Result = "+serverResponse);
if(api.result == 1){
subscriptionModalArrayList.add(new Subscription(packageName,purchaseCode));
Intent intent = new Intent(MainActivity.this, ValidationResult.class);
startActivity(intent);
}
if(api.result == 0){
Toast.makeText(MainActivity.this, "Inactive Subscription", Toast.LENGTH_LONG).show();
System.exit(1);
}
if(serverResponse == 2 || serverResponse == 3){
Toast.makeText(MainActivity.this, "Failed to fetch data from API or other Error...", Toast.LENGTH_LONG).show();
System.exit(1);
}
txtPackageName.setText("");
txtPurchaseCode.setText("");
}
});
}
}
The request you are making is asynchronous and you must wait to get the response from it.
The behavior you are seeing (always returning zero) because the result variable has not been initialized and defaults to zero.
public static int result;
You can pass a callback to your checkSubscription method which will be called when you have a result from the request (either failure or success).
You can do this by defining an interface like so:
public interface Callback {
public void onSuccess(int result);
public void onFailure(String error);
}
And making your activity implement this method:
public class MainActivity extends AppCompatActivity implements Callback {
...
public void onSuccess(int result) {
//Your logic here
}
public void onFailure(String error) {
//Your logic here
}
}
And make sure to pass the activity to your API:
public int checkSubscription(String packageName, String purchaseCode, RequestQueue q, Callback callback) {
.....
callback.onSuccess(result)
public void onErrorResponse(VolleyError error) {
result = 3;
System.out.println("Result in Api = Failed to get the data...");
callback.onError("YOUR_ERROR_MESSAGE");
}
}
Disclaimer : the above code is just a rough outline and should be
tested

Not able to print JSON object String in android TextView

So I am trying to fetch JSON string from a website which looks like this
[{"name":"Painting"},{"name":"Painting or varnishing doors"},{"name":"Painting or varnishing frames"},{"name":"Varnishing floors"},{"name":"Picking old wallpaper"},{"name":"Painting the facade"},{"name":"professional athlete"}]
I just want to fetch the first JSONObject with the string "Painting".
Here's my MainActivity.java code
package mobiletest.pixelapp.com.mobiletest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import model.Cup;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private String myString;
private String anotherString;
private String myVar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
Cup myCup = new Cup();
String newString = myCup.myMethod();
try {
JSONArray jsonArray = new JSONArray(newString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.v("Key",jsonObject.getString("name"));
textView.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here's my java class file cup.java
package model;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by pruthvi on 12/2/2015.
*/
public class Cup {
public String myMethod()
{
String output = getUrlContents("http://xyz.co/tests/android-query.php");
return output;
}
private static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
// many of these calls can throw exceptions, so i've just
// wrapped them all in one try/catch statement.
try
{
// create a url object
URL url = new URL(theUrl);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
Now the problem, when I run this code as java I am easily able to print painting from the JSONObject, but when I try to run it as an android view by setting the text for my TextView, I am getting some strange system.err
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest D/libc: [NET] getaddrinfo hn 10, servname NULL, ai_family 0+
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:393)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:244)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:219)
I am new to java and android, and as of now I just want to get data from my remote server files and database.
Thanks in advance
look at this example it will give you an idea
AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
URL url = new URL("http://www.omdbapi.com/?i=&t="
+ TITLE);
String URL2="http://www.omdbapi.com/?i=&t=saw";
Log.d("URL content", url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
Log.d("URL content", "register URL");
urlConnection.connect();
Log.d("URL connection", "establish connection");
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
};
asyncLoad.execute();
Do like that in onCrate Method
try {
JSONArray jsonArray = new JSONArray(newString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name")
textView.setText(name));}
} catch (JSONException e) {
e.printStackTrace();
}
It will set name to textView.
Happy to Help and Happy Coding
You can't do network task in UI Thread.
So
String newString = myCup.myMethod();
not properly working.
Main Reason of those errors are related with thread context.
If you want to do network task with android, use async task or other network library (personally I recommend retrofit).
try
{
JSONArray jsonArray = new JSONArray(newString);
if(jarray.length()>0){
String name = jarray.getJSONObject(0).getString("name");
displayName(name); //new method
}catch(Exception e){
}
Define the method displayName(String) like this outside onCreate()
public void displayName(final String name){
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(jsonObject.getString("name"));
}
});
}

Android - after notifyDataSetChanged ListView remains blank

It's hours I search for something, but it doesn't seem to help.. Android Studio doesn't launch any error, but the screen remains blank. Why?
package org.newapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import saxrssreader.*;
public class MainActivity extends Activity {
private ArrayAdapter<RssItem> rssItemsArrayAdapter;
ListView codeLearnLessons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RssItem[] rssItems = new RssItem[]{};
rssItemsArrayAdapter = new ArrayAdapter<RssItem>(this, android.R.layout.simple_list_item_1, rssItems);
new WebCall().execute(rssItems);
codeLearnLessons = (ListView)findViewById(R.id.listView1);
codeLearnLessons.setAdapter(rssItemsArrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class WebCall extends AsyncTask<RssItem, Void, Void> {
#Override
protected Void doInBackground(RssItem... items) {
URL url = null;
try {
url = new URL("http://www.somewpsite.com/feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
ArrayList<RssItem> listItems = RssReader.read(url).getRssItems();
items = listItems.toArray(new RssItem[listItems.size()]);
final int l = items.length;
runOnUiThread(new Runnable() {
#Override
public void run() {
codeLearnLessons.invalidateViews();
rssItemsArrayAdapter.notifyDataSetChanged();
Log.i("rec", "rec" + l);
}
});
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
/*ProgressDialog mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Please wait...");
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mDialog.setCancelable(false);
mDialog.show();*/
}
}
}
The issue is that your using a ArrayList which only has scope inside of the AsyncTask.doInBackground() method. Since it is not given to the adapter, the notifyDataSetChanged() does nothing. You'll need to replace the existing array like this:
rssItemsArrayAdapter.clear();
rssItemsArrayAdapter.addAll(listItems);
rssItemsArrayAdapter.notifyDataSetChanged();
Having said that, you also really need to change your use of AsyncTask. There's no need to call runOnUiThread() from within your doInBackground() as the AsyncTask will automatically run its onPostExecute() on the UI thread. Have your doInBackground() method return your new ArrayList<RssItem> and create an onPostExecute() override method which adjusts the adapter as shown above.
You are passing your items to the AsyncTask but in the AsyncTask you declare them new with the content of your result. You never pass the items to your ArrayAdapter back. Make them a property of your class instance.
Edit - Example:
rssItemsArrayAdapter.clear();
rssItemsArrayAdapter.addAll(items);
and afterwards
rssItemsArrayAdapter.notifyDataSetChanged();

Consuming Restful WCF Service in Android

I am not sure what causing the request not to execute. I was trying to call a WCF Restful service in android, and I receive the error message "Request Error". Looking at the example, I don't see any reason why this example should not work. See below:
Here is the .Net Service:
[ServiceContract]
public interface ISampleService
{
[OperationContract]
[WebInvoke(
Method="POST", UriTemplate="/Login", BodyStyle= WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string Login(string value);
}
public class SampleService : ISampleService
{
public string Login(string value)
{
string t = "";
try
{
//foreach (string s in value)
//{
// t = s;
//}
return t;
}
catch (Exception e)
{
return e.ToString();
}
}
}
Java:
package com.mitch.wcfwebserviceexample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {
private String values ="";
Button btn;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)this.findViewById(R.id.btnAccess);
tv = (TextView)this.findViewById(R.id.tvAccess);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
try
{
AsyncTaskExample task = new AsyncTaskExample(this);
task.execute("");
String test = values;
tv.setText(values);
} catch(Exception e)
{
Log.e("Click Exception ", e.getMessage());
}
}
public class AsyncTaskExample extends AsyncTask<String, Void,String>
{
private String Result="";
//private final static String SERVICE_URI = "http://10.0.2.2:8889";
private final static String SERVICE_URI = "http://10.0.2.2:65031/SampleService.svc";
private MainActivity host;
public AsyncTaskExample(MainActivity host)
{
this.host = host;
}
public String GetSEssion(String URL)
{
boolean isValid = true;
if(isValid)
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:65031/SampleService.svc/Login");
try
{
List<NameValuePair> value = new ArrayList<NameValuePair>(1);
value.add(new BasicNameValuePair("value", "123456"));
post.setEntity(new UrlEncodedFormEntity(value));
HttpResponse response = client.execute(post) ;
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line ="";
while((line = rd.readLine()) != null)
{
System.out.println(line);
}
}catch(Exception e)
{
Log.e("Error", e.getMessage());
}
}
return Result;
}
#Override
protected String doInBackground(String... arg0) {
android.os.Debug.waitForDebugger();
String t = GetSEssion(SERVICE_URI);
return t;
}
#Override
protected void onPostExecute(String result) {
// host.values = Result;
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
}
}
I finally got it to work they way that I want it to. The issue was that I was building the Array this way (see below section 1) and pass it to the JSONObject or JSONArray. I switched and build the Array using JSONArray and pass it to the JSONObject (see section 2). It works like a charm.
Section1: Wrong way to do it - (It may work this way if you were to look through the array and put them in a JSONArray. It's will be too much work when it can be done directly.)
String[][] Array = {
new String[]{"Example", "Test"},
new String[]{"Example", "Test"},
};
JSONArray jar1 = new JSONArray();
jar1.put(0, Array);
// Did not work
Section 2: The way I did it after long hours of trying and some very helpful tips and hints from #vorrtex.
**JSONArray jar1 = new JSONArray();
jar1.put(0, "ABC");
jar1.put(1, "Son");
jar1.put(2, "Niece");**
**JSONArray jarr = new JSONArray();
jarr.put(0, jar1);**
JSONArray j = new JSONArray();
j.put(0,"session");
JSONObject obj = new JSONObject();
obj.put("value", jarr);
obj.put("test", j);
obj.put("name","myName");
Log.d("Obj.ToString message: ",obj.toString());
StringEntity entity = new StringEntity(obj.toString());
Looking at the web service, and it has exactly what I was looking for.
Thanks for you help!!!!

Using AsyncTask, but experiencing unexpected behaviour

Please refer to the following code which continuously calls a new AsyncTask. The purpose of the AsyncTask is to make an HTTP request, and update the string result.
package room.temperature;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class RoomTemperatureActivity extends Activity {
String result = null;
StringBuilder sb=null;
TextView TemperatureText, DateText;
ArrayList<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TemperatureText = (TextView) findViewById(R.id.temperature);
DateText = (TextView) findViewById(R.id.date);
nameValuePairs = new ArrayList<NameValuePair>();
for (int i = 0; i < 10; i++) {
RefreshValuesTask task = new RefreshValuesTask();
task.execute("");
}
}
// The definition of our task class
private class RefreshValuesTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/roomtemp/tempscript.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine());
is.close();
result=sb.toString();
}
catch(Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//System.out.println(result);
setValues(result);
}
}
public void setValues(String resultValue) {
System.out.println(resultValue);
String[] values = resultValue.split("&");
TemperatureText.setText(values[0]);
DateText.setText(values[1]);
}
}
The problem I am experiencing relates to the AsyncTask in some way or the function setValues(), but I am not sure how. Essentially, I want each call to the AsyncTask to run, eventually in an infinite while loop, and update the TextView fields as I have attempted in setValues. I have tried since yesterday after asking a question which led to this code, for reference.
Oh yes, I did try using the AsyncTask get() method, but that didn't work either as I found out that it is actually a synchronous call, and renders the whole point of AsyncTask useless.
Use publishProgress(), and onProgressUpdate() methods, to publish progress, while executing some task in doInBackground() method.
so change your code to following:
package room.temperature;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class RoomTemperatureActivity extends Activity {
String result = null;
StringBuilder sb=null;
TextView TemperatureText, DateText;
ArrayList<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TemperatureText = (TextView) findViewById(R.id.temperature);
DateText = (TextView) findViewById(R.id.date);
nameValuePairs = new ArrayList<NameValuePair>();
RefreshValuesTask task = new RefreshValuesTask();
task.execute("");
}
// The definition of our task class
private class RefreshValuesTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
for (int i = 0; i < 10; i++) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/roomtemp/tempscript.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine());
is.close();
result=sb.toString();
publishProgress(result);
}
catch(Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
return result;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
setValues(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//System.out.println(result);
setValues(result);
}
}
public void setValues(String resultValue) {
System.out.println(resultValue);
String[] values = resultValue.split("&");
TemperatureText.setText(values[0]);
DateText.setText(values[1]);
}
}

Categories