Android - onPostExecute Result doesn't receive info - java

I have two codes inside the doInBackground, but only the second passes the data to the onPostExecute.
Already tried to debug the code, but it wasn't much helpful. The webservice that I'm using is fully functional, I think.
public void onClickWheater(View view){
new HttpAsyncTask().execute(opa);
}
class HttpAsyncTask extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
#Override
protected String doInBackground(String... params) {
if(params.equals(opa)){
try {
HttpGet get = new HttpGet("http://ghelfer.net/weather.aspx?output=json");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
return data;
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
HttpGet get = new HttpGet("https://viacep.com.br/ws/" + params[0] + "/json/");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(get);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
return data;
}
} catch (Exception e) {
return null;
}
}
return null;
}
Edit - PostExecute
#Override
public void onPostExecute(String result){
dialog.dismiss();
if (result != null){
try{
JSONObject obj = new JSONObject(result);
String logradouro = obj.getString("logradouro");
String complemento = obj.getString("complemento");
String bairro = obj.getString("bairro");
String localidade = obj.getString("localidade");
String uf = obj.getString("uf");
txtLogradouro.setText(logradouro);
txtComplemento.setText(complemento);
txtBairro.setText(bairro);
txtLocalidade.setText(localidade);
txtUF.setText(uf);
JSONObject res = new JSONObject(result);
JSONArray weather = res.getJSONArray("weather");
int dataLength = weather.length();
double avgTemp = 0.0;
double avgHumid = 0.0;
double tempSum = 0.0;
double humidSum = 0.0;
for (int i = 0; i < dataLength; i++) {
JSONObject tempObj = weather.getJSONObject(i);
tempSum += tempObj.getDouble("temperature");
humidSum += tempObj.getDouble("humidity");
}
if (dataLength != 0) {
avgTemp = tempSum/dataLength;
avgHumid = humidSum/dataLength;
}
String temp = Double.toString(avgTemp);
txtTemperature.setText(temp);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Can't get the value from doInBackGround() process at onPostExecute()

I'm using AsyncTask to insert, update and delete data from database. I used this code to insert, update, delete and it works fine. But when I want to use select, and show the data at EditText, I can't get the value from doInBackground() to the onPostExecute() and it shows nothing.
Here's my code :
MenuUtama.java
public class MenuUtama extends Activity {
/** Called when the activity is first created. */
private TextView nama_user;
private String nm_user = "";
private EditText kode, nama, harga, deskripsi;
private Button insert, update, delete, cek;
private String kode1, nama1, harga1, deskripsi1;
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
kode = (EditText) findViewById(R.id.editKode);
nama = (EditText) findViewById(R.id.editNama);
harga = (EditText) findViewById(R.id.editHarga);
deskripsi = (EditText) findViewById(R.id.editDes);
cek = (Button) findViewById(R.id.btnCek);
insert = (Button) findViewById(R.id.buttonInsert);
update = (Button) findViewById(R.id.buttonUpdate);
delete = (Button) findViewById(R.id.buttonDelete);
nama_user = (TextView) findViewById(R.id.textView3);
Intent i = getIntent();
nm_user = i.getStringExtra("nama_user");
nama_user.setText(nm_user);
insert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=insert&kd=" + ko + "&nm=" + n + "&hrg=" + hr + "&deskripsi=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=update&kd=" + ko + "&nm=" + n + "&hrg=" +hr+ "&des=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=delete&kd=" + kode1;
new CRUD().execute(url);
}
});
cek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=read&kd="+kode1;
new CRUD().execute(url);
}
});
}
public class CRUD extends AsyncTask<String, String, String> {
String success;
String kode_d, nama_d, harga_d, des_d;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(params[0]);
try {
success = json.getString("success");
Log.e("error", "nilai sukses=" + success);
JSONArray hasil = json.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < hasil.length(); i++) {
JSONObject c = hasil.getJSONObject(i);
kode_d = c.getString("kd");
nama_d = c.getString("nm");
harga_d = c.getString("hrg");
des_d = c.getString("deskripsi");
}
}
else {
Log.e("erro", "tidak bisa ambil data 0");
}
}
catch (Exception e) {
// TODO: handle exception
Log.e("erro", "tidak bisa ambil data 1");
}
return kode_d;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
kode.setText(kode_d);
nama.setText(nama_d);
harga.setText(harga_d);
deskripsi.setText(des_d);
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +e.toString());
}
// return JSON String
return jObj;
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +e.toString());
}
// return JSON String
return jObj;
}
}
It is because you don't return any value from the doInBackground() (always return null) and you are not using the 'string' in the onPostExecute(String result) formal parameter. Garbage-In-Garbage-Out
your doInBackground() returns just a string return kode_d; and then in your onPostExecute(String result) (which expects a String) you use the kode_d which is null.
If you want all of those values to be returned create an ArrayList(), return it at the end doInBackground() and get it in onPostExecute(ArrayList result) with an iteration and pass it to you textviews.
Even better create an object and add the values to each field. Your fields are the kode_d, nama_d, harga_d, des_d
this is what the onPostExecute does
/**
* <p>Runs on the UI thread after {#link #doInBackground}. The
* specified result is the value returned by {#link #doInBackground}.
* To better support testing frameworks, it is recommended that this be
* written to tolerate direct execution as part of the execute() call.
* The default version does nothing.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* #param result The result of the operation computed by {#link #doInBackground}.
*
* #see #onPreExecute
* #see #doInBackground
* #see #onCancelled(Object)
*/

JSON: Value of type java.lang.String cannot be converted to JSONObject

I'm trying to program an app to send a String to a service. A friend of mine has a service to receive the data.
Logcat shows this error: "org.json.JSONException: Value FIRST of type java.lang.String cannot be converted to JSONObject"
Here is my code:
Main Activity
public class MainActivity extends Activity {
private String URL = "String with my friend's url";
private Button btnAddValue;
String num = "1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup answer = (RadioGroup) findViewById(R.id.answer);
answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answerA:
num = "1";
break;
case R.id.answerB:
num = "2";
break;
case R.id.answerC:
num = "3";
break;
}
}
});
btnAddValue = (Button) findViewById(R.id.submit);
btnAddValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new AddNewValue().execute(num);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class AddNewValue extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... arg) {
// TODO Auto-generated method stub
String number = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("number", number));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL,
ServiceHandler.POST, params);
Log.d("Create Request: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
Log.e("Value added successfully ",
"> " + jsonObj.getString("message"));
} else {
Log.e("Add Error: ",
"> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "JSON data error!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Service Handler
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
I read questions to other people with the same problem. The solution seemed to be to add a "{" at the beginning of the json String and a "}" at the end, but it didn't work to me. I tried changing this:
String json = serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params);
to this:
String json = "{" + serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params) + "}";
but the I got this error:
"org.json.JSONException: Expected ':' after FIRST at character 9 of {FIRST DATA New record created successfully}"
You're receiving back a string that is not able to be parsed to JSON. You can't just make something JSON by adding braces, it needs to adhere to proper JSON formatting. This site shows some good examples of what that means.
Specifically, the parser is telling you that having a space after FIRST isn't okay without having quotes around it...but just adding that won't fix the issue, the problem is more deep than that.

How to access json array that is passed from restful web service in android?

I have successfully created a rest web service and it returns jsonarray which has two fields
id and city from data base.
My resr web service is
#GET
#Path("city")
#Produces("application/json")
public String getJson() {
PropertyPojo propojo=null;
ArrayList cityList = new ArrayList();
JSONArray list = new JSONArray();
Map m1 = new LinkedHashMap();
List l1 = new LinkedList();
String jsonString = null;
try{
cityList=PDao.CityList();
Iterator it=cityList.iterator();
while(it.hasNext())
{
propojo=(PropertyPojo)it.next();
m1.put(propojo.getKeyid(),propojo.getKeyvalue());
}
}catch(Exception e){
}
l1.add(m1);
jsonString = JSONValue.toJSONString(l1);
return jsonString;
}
I just need to put these values into a spinner...
My android code is
public class MainActivity extends Activity {
Spinner spinner;
private static final String SERVICE_URL = "http://192.168.1.6:8080/eSava_RestWeb/webresources/service";
private static final String TAG = "AndroidRESTClientActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.city);
}
public void retrieveSampleData(View vw) {
String sampleURL = SERVICE_URL + "/city";
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK,
this, "GETting data...");
wst.execute(new String[] { sampleURL });
}
#SuppressLint("NewApi")
public void handleResponse(String response) {
try {
// JSONObject jso = new JSONObject(response);
JSONArray json = new JSONArray(response);
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray) json;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
list.add(jsonArray.get(i).toString());
}
}
Spinner s = (Spinner) findViewById(R.id.city);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, list);
s.setAdapter(adapter);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext,
String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity()
.getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
JSONArray jsArray;
// jsArray = new JSONArray(response);
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
}
Its better to create Model class and then you can parse the response with gson.
For example,
Imagine that you have your response with two strings Name and Mail. Create a model with two strings.
public class Sample{
public Sample()
{
}
#SerializedName("Name")//if needed
String name;
#SerializedName("Email")//if needed
String email;
public void set(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void set(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
Then parse your response with gson.
Sample sample = gson.fromJson(jsonRes.toString(), Sample.class);
Then you can access the members of the object sample. Change the Sample class as you needed(with the array of strings and int. You can use ArrayList instead of Array)
String[] city= {};
String[] id= {};
JSONArray jsonDetailsObj = json.getJSONArray("cityList");
JSONObject jsonLoop = null;
int noOfPoints = jsonDetailsObj.length();
city= new String[noOfPoints];
id= new String[noOfPoints];
for (int i=0 ; i < noOfPoints ; i++)
{
jsonLoop=jsonDetailsObj.getJSONObject(i);
city [i] = jsonLoop.getString("CityName");
id[i] = jsonLoop.getString("ID");
}

Android Error Returning a null value from Thread

I created this application to get the wether details to my app.
I have a GetWeather Class in my Android App whre i have GetWeather method which returns a string. but when i try to get value form that class which consist of a thread. i always get a null value. Please refer my code kindly and tell me where i got wrong. Thank you
Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.showData);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
GetWeather1 gw = new GetWeather1();
String weather = gw.GetWeather1 ("CA","Anuradhapura");
Toast.makeText(getApplicationContext(), " Weather condition is " + weather, Toast.LENGTH_SHORT).show();
}
});
}
// This is GetWeather class
public class GetWeather {
public String weather;
public String temperature_string;
public Bitmap weather_icon;
public GetWeather() {
}
public String GetWeather(String city, String state) {
city = city.replaceAll(" ", "_");
// construct post URL
final String GET_WEATHER_URL = WEATHER_URL + state + "/" + city
+ ".json";
new Thread(new Runnable() {
public void run() {
String request = GET_WEATHER_URL;
HttpResponse rp = null;
JSONObject jObject = null;
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpGet request1 = new HttpGet(
"http://api.wunderground.com/api/key/conditions/q/CA/Anuradhapura.json");
HttpResponse response = httpclient.execute(request1);
HttpEntity resEntity = response.getEntity();
String _response = EntityUtils.toString(resEntity);
jObject = new JSONObject(_response);
JSONObject current_observation = jObject.getJSONObject("current_observation");
temperature_string = current_observation.getString("temperature_string");
weather = current_observation.getString("weather");
Log.i("..............", "" + weather);
Log.i("..............", "" + temperature_string);
String icon_url = current_observation.getString("icon_url");
weather_icon = get_weather_icon(icon_url);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
while (weather != null) {
}
return weather;
}
The condition while(whether != null) should be while(whether == null) to wait for a Thread to complete its task. But it will wait on UI Thread which may result in ANR error.
Instead use AsyncTask and get the result in onPostExecute()...
and with respect to your comments, This may help you.
public class WeatherTask extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
String city = params[0];
String state = params[1];
city = city.replaceAll(" ", "_");
// construct post URL
final String GET_WEATHER_URL = WEATHER_URL + state + "/" + city
+ ".json";
String request = GET_WEATHER_URL;
HttpResponse rp = null;
JSONObject jObject = null;
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpGet request1 = new HttpGet(
"http://api.wunderground.com/api/key/conditions/q/CA/Anuradhapura.json");
HttpResponse response = httpclient.execute(request1);
HttpEntity resEntity = response.getEntity();
String _response = EntityUtils.toString(resEntity);
jObject = new JSONObject(_response);
JSONObject current_observation = jObject
.getJSONObject("current_observation");
String temperature_string = current_observation
.getString("temperature_string");
String weather = current_observation.getString("weather");
Log.i("..............", "" + weather);
Log.i("..............", "" + temperature_string);
String icon_url = current_observation.getString("icon_url");
String weather_icon = get_weather_icon(icon_url);
String[] out = new String[]{weather,weather_icon,temperature_string};
return out;
} catch (Exception exception) {
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
if(result != null) {
String weather = result[0];
String weather_icon = result[1];
String temperature_string = result[2];
}
}
}
and start this task in onButtonClick() like
new WeatherTask().execute("CA","Anuradhapura");

how to consume json web service deployed in iis in android

i have created restfull webservices (retun json data) in asp.net and deploye it on iis.now i want to consume that webServices in android..but in android its work fine in emulator but on android device its give error...
Error: Connection to" //http://ipAddress.:6547/" refused
plz help
thats code
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_jsonws_map_layout);
}
public String readJSONFeed(String URL)
{
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try
{
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
inputStream.close();
}
else
{
Log.d("JSON", "Failed to download file");
}
}
catch (Exception e)
{
Log.e("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
#SuppressWarnings("unused")
private class ReadWeatherJSONFeedTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result)
{
try
{
jsonObject = new JSONObject(result);
jsonArrayGeoPoint = new JSONArray(jsonObject.getString("jsondataResult").toString());
Toast.makeText(getApplicationContext(), jsonArrayGeoPoint.getString(0).toString()+"||"+jsonArrayGeoPoint.getString(1).toString(), Toast.LENGTH_SHORT).show();
String[] strArrtemp=new String[5];
Double[] strArrLat = new Double[5];
Double[] strArrLon = new Double[5];
for(int i=0; i<jsonArrayGeoPoint.length(); i++)
{
try
{
strArrtemp[i]=jsonArrayGeoPoint.getString(i).toString();
}
catch (JSONException e)
{
Log.e("JsonArray ERROR",e.getLocalizedMessage());
}
}
String[] arrytemp = new String[2];
String temp;
for(int i=0; i<strArrtemp.length; i++)
{
temp = strArrtemp[i].toString();
strArrLat[i]=Double.parseDouble(temp.substring(0,6));
strArrLon[i]=Double.parseDouble(temp.substring(7,13));
}
Toast.makeText(getApplicationContext(), "Lat1="+strArrLat[1].toString()+" & Lon1="+strArrLon.toString(), Toast.LENGTH_SHORT).show();
Button getDir;
getDir = (Button)findViewById(R.id.getLocationBtn);
getDir.setText(strArrLat[1].toString());
}
catch (Exception e)
{
Log.e("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}
enter code here
public void btnGetWeather(View view)
{ newReadWeatherJSONFeedTask().execute(http://ipAddress.:6547/RestServiceImpl.svc/jsondata/");
}
}
instead of using localhost use 10.0.2.2:portnumber

Categories