Using AsyncTask, but experiencing unexpected behaviour - java

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]);
}
}

Related

How to Pretty-Print , JSON raw datas on Android [duplicate]

This question already has answers here:
Convert JSON String to Pretty Print JSON output using Jackson
(11 answers)
Closed 6 years ago.
I have an API in JSON , my json datas are displayed raw on my android application , i want them to be displayed in pretty print format like this
Not like this
This is my java code :
package com.example.cbmedandroid;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
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.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://10.0.2.2:8000/api/horaire.json");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
How to do that ?
Thanks
You need to use a JSON library like Jackson or GSON in order to pretty print your output. For an example with Jackson take a look at the answer here.

Error when connecting to online database

I am trying to connect to an external database on my server via AsyncTask but Eclipse is showing me an error in the log-
See the error image.
Here is the code I am using-
MainActivity.java:
package com.deltware.newco;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView res;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.res = (TextView) this.findViewById(R.id.textView1);
this.btn1 = (Button) this.findViewById(R.id.button1);
this.btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new getAllUsersTask().execute(new Connector());
}
});
}
public void setTextToView(JSONArray json){
String s= "";
for(int i = 0; i<json.length(); i++){
JSONObject jo = null;
try{
jo = json.getJSONObject(i);
s += "Name: " + jo.getString("name") +
"Email: " + jo.getString("email");
}catch(JSONException e){
e.printStackTrace();
}
}
this.res.setText(s);
}
private class getAllUsersTask extends AsyncTask<Connector, Long,JSONArray>{
#Override
protected JSONArray doInBackground(Connector... param) {
return param[0].getAllUsers();
}
#Override
protected void onPostExecute(JSONArray result) {
setTextToView(result);
}
}
}
Connector.java:
package com.deltware.newco;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.DefaultedHttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class Connector {
public JSONArray getAllUsers(){
String url = "url to the location of my php file";
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
httpEntity = httpResponse.getEntity();
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
JSONArray json = null;
if(httpEntity == null){
try{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response:",entityResponse);
json = new JSONArray(entityResponse);
}catch(JSONException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
return json;
}
}
PHP file:
$query = mysqli_query($db, "SELECT name, email, gender FROM users");
while($row = mysqli_fetch_assoc($query)){
$ouput[] = $row;
}
echo json_encode($ouput);
I am using Eclipse and Android 4.4 KitKat.

Parsing JSON Result Android [duplicate]

This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 7 years ago.
I am building an Android application that receives some data in JSON format. At the moment the result is very ugly. I want to display this data neatly in multiple TextViews in my application but I am not to sure how to do it. Source code below.
Main.java
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
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.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity implements OnClickListener {
TextView txt1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("https://api.myjson.com/bins/363s3");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
txt1 = (TextView)findViewById(R.id.textView1);
txt1.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
i use retrofit for asynchronous execution use Callback
If what u mean is how to structure the data u receive from the json then you should look into json formatting frameworks (like 'Jackson' or 'Gson' or others).
If what u mean is how to make the textual json appear neatly in a textbox, jackson also appears to have an option to print the json neatly (try this: http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/ )
What about trying something like,
JSONObject jsonObject = new JSONObject(jsonString);
By the way, Volley is a good library for any kind of requests.

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!!!!

Android php+mysql+json error implementing AsyncTask

Im new to Android and I need a little help. I have a class witch values from one table located on remote mysql and its working fine on 2.3 but on 4.x Im getting errors when I start it. I have read somewhere its because I`m not using AsyncTask. I tried to implement it on existing working code but there is one error, so please help because I tried everything to get this to work but no success.
Here is the existing code that works on 2.3
package com.stole.fetchtest;
import java.io.BufferedReader;
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.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("names"));
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
}
}}
And then I tried to add AsyncTask, according to some tutorials found online, and it`s looking like this:
package com.stole.fetchtest;
import java.io.BufferedReader;
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.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new task().execute();
}
public class task extends AsyncTask<String, String, Void> {
#SuppressWarnings("unchecked")
#Override
protected Void doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("naziv"));
}
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
}
}
}
}
The error I`m getting is at
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
and it says "The constructor ArrayAdapter(FetchData.task, int, List) is undefined"
Thanks!
it should use the activity context not the task context..
setListAdapter(new ArrayAdapter(FetchData.this, R.layout.names_row, r));

Categories