Can't set spinner Adapter from AsyncThread - android

I am fetching some data from php and trying to show that data in spinner through arrayadater, but there is a prob can
**DownloadDetails downloaddeatils = new DownloadDetails(this);
downloaddeatils.execute(url);
public class DownloadDetails extends AsyncTask<String, Void, String> {
Context context;
ProgressDialog progressDialog;
public DownloadDetails(Context context) {
this.context = context;
progressDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Fetching Data, please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... urls) {
String output = null;
for(String url: urls) {
output = getOutputFromUrl(url);
}
return output;
}**
private String getOutputFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject object = null;
JSONObject object1 = null;
JSONObject object2 = null;
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("speciality_id", sid));
nameValuePairs.add(new BasicNameValuePair("type",type));
nameValuePairs.add(new BasicNameValuePair("condition_id", cid));
nameValuePairs.add(new BasicNameValuePair("locality", locality));
nameValuePairs.add(new BasicNameValuePair("city_name", city_name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpPost,
responseHandler);
Log.d("Respone",responseBody);
if(!responseBody.equals(null))
{
JSONObject jsonResponse = new JSONObject(responseBody);
object = jsonResponse.getJSONObject("firstarray");
object1 = jsonResponse.getJSONObject("secondarray");
object2 = jsonResponse.getJSONObject("thirdarray");
try {
if (!object.toString().trim().contains("null")) {
Log.d("Inside ","count"+count);
if (count == 0) {
JSONArray jArray = object.getJSONArray("values");
for (int i = 0; i < jArray.length(); i++) {
String str = jArray.getString(i).substring(0,
jArray.getString(i).length());
String[] data = str.split("_");
specialistList.add(data[0]);
specialistNameList.add("" + data[1]);
//specialistAdapter.add("" + data[1]);
}
//specialistAdapter.setNotifyOnChange(true);
count = 1;
}
}
if (!object1.toString().trim().contains("null")) {
JSONArray JArray1 = object1.getJSONArray("values1");
for (int i = 0; i < JArray1.length(); i++) {
String str = JArray1.getString(i).substring(0,
JArray1.getString(i).length());
String[] data = str.split("_");
conditionList.add(data[0]);
//conditionAdapter.add(data[1]);
conditionNameList.add(data[1]);
}
//conditionAdapter.setNotifyOnChange(true);
Log.d("Inside","SecondArray");
}
if (!object2.toString().trim().contains("null")) {
JSONArray JArray1 = object2.getJSONArray("values2");
for (int i = 0; i < JArray1.length(); i++) {
String str = JArray1.getString(i).substring(0,
JArray1.getString(i).length());
String[] data = str.split("_");
doctorIdList.add(data[0]);
doctorNameList.add(data[1]);
// adapter.add(data[1]);
}
// adapter.setNotifyOnChange(true);
}
} catch (Exception e) {
Log.d("Unknown exception",""+e);
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(),"Unable to fetch data from server",Toast.LENGTH_LONG).show();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String output) {
super.onPostExecute(output);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
for(int i=0;i<specialistNameList.size();i++)
specialistAdapter.add(specialistNameList.get(i));
for(int j=0;j<conditionNameList.size();j++)
conditionAdapter.add(conditionNameList.get(j));
for(int k=0;k<doctorNameList.size();k++)
adapter.add(doctorNameList.get(k));
}
if(output != null) {
Toast.makeText(getApplicationContext(), "Cannot connect to Server",Toast.LENGTH_LONG).show();
}
else {
}
}
}

You should write code, which modify event thread, in onPostExecute(), or onPreExecute(), or onPublishedProgress() methods, not in doInBackground() methods.

Related

sort two array list simuntaneously in one activity

I am working on application in which i want one output as shown in below image.
for that i tried following code:
private ListView notification_listview;
private String BeauticianId="98";
private String serviceType="all";
private ArrayList<NameValuePair> params11;
ArrayList<MainArray_method> MainList;
MainArray_adapter main_adapter;
ArrayList<SubArray_method> SubList;
SubArray_adapter sub_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification_listview = (ListView) findViewById(R.id.listView_notification);
}
#Override
public void onResume() {
super.onResume();
params11 = new ArrayList<NameValuePair>();
params11.add(new BasicNameValuePair("iBeauticianId", BeauticianId));
params11.add(new BasicNameValuePair("serviceType", serviceType));
new background().execute();
}
private class background extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/services", params11);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result", "" + result);
try {
JSONObject json = new JSONObject(result);
String status = json.getString("status");
Log.d("Status:", status);
String data = json.getString("data");
Log.d("Data:", data);
MainList = new ArrayList<MainArray_method>();
JSONArray MainArray = json.getJSONArray("data");
for (int i = 0; i < MainArray.length(); i++) {
JSONObject jsonObject = MainArray.getJSONObject(i);
String MainServiceId = jsonObject.getString("iMainServiceId");
Log.d("MainServiceId:", MainServiceId);
String MainService = jsonObject.getString("main");
Log.d("MainService:", MainService);
String sub = jsonObject.getString("sub");
Log.d("sub:", sub);
SubList = new ArrayList<SubArray_method>();
JSONArray SubArray = jsonObject.getJSONArray("sub");
for (int j = 0; j < SubArray.length(); j++) {
/*JSONObject subjsonObject = SubArray.getJSONObject(j);*/
/*String SubServiceId = subjsonObject.getString("iSubServiceId");
Log.d("subserviceid:", SubServiceId);
String SubServiceName = subjsonObject.getString("vName");
Log.d("SubServiceName:", SubServiceName);
String SubServicePrice = subjsonObject.getString("fPrice");
Log.d("SubServicePrice:", SubServicePrice);
String SubServiceTime = subjsonObject.getString("vDuration");
Log.d("SubServiceTime:", SubServiceTime);*/
MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
MainArray.getJSONObject(i).getString("main")));
SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
SubArray.getJSONObject(j).getString("vName"),
SubArray.getJSONObject(j).getString("fPrice"),
SubArray.getJSONObject(j).getString("vDuration")));
}
}
if (main_adapter== null && sub_adapter == null)
{
main_adapter=new MainArray_adapter(getApplicationContext(),MainList);
notification_listview.setAdapter(main_adapter);
sub_adapter=new SubArray_adapter(getApplicationContext(),SubList);
notification_listview.setAdapter(sub_adapter);
} else {
sub_adapter.notifyDataSetChanged();
main_adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
pDialog.dismiss();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// 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();
} 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);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
but in this i just get two record of subarray.
What should i do to get output as shown in image.
Thanks in advance.
JSON response:
{
"status":1,
"data":[
{
"iMainServiceId":1,
"main":"NAILS",
"sub":[
{
"iSubServiceId":1,
"vName":"Manicure",
"fPrice":15,
"vDuration":"20 Minutes"
},
{
"iSubServiceId":2,
"vName":"Gel Manicure",
"fPrice":25,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":5,
"vName":"Nail art ",
"fPrice":10,
"vDuration":"20 Minutes"
},
{
"iSubServiceId":6,
"vName":"Nail Pain ",
"fPrice":10,
"vDuration":"20 Minutes"
}
]
},
{
"iMainServiceId":2,
"main":"HAIR",
"sub":[
{
"iSubServiceId":3,
"vName":"Haircuts",
"fPrice":20,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":4,
"vName":"Hair color",
"fPrice":50,
"vDuration":"60 Minutes"
},
{
"iSubServiceId":7,
"vName":"Textures",
"fPrice":20,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":8,
"vName":"Treatments",
"fPrice":30,
"vDuration":"60 Minutes"
}
]
},
{
"iMainServiceId":3,
"main":"Face",
"sub":[
{
"iSubServiceId":9,
"vName":"Facials",
"fPrice":20,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":10,
"vName":"Brow Bar",
"fPrice":40,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":11,
"vName":"Makeup ",
"fPrice":40,
"vDuration":"49 Minutes"
}
]
},
{
"iMainServiceId":4,
"main":"Body",
"sub":[
{
"iSubServiceId":12,
"vName":"Hair Removal",
"fPrice":40,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":13,
"vName":"Body Treatments",
"fPrice":30,
"vDuration":"30 Minutes"
}
]
}
]
}
and wt i get as enter image description hereoutput is:
for (int i = 0; i < MainArray.length(); i++) {
JSONObject jsonObject = MainArray.getJSONObject(i);
String MainServiceId = jsonObject.getString("iMainServiceId");
Log.d("MainServiceId:", MainServiceId);
String MainService = jsonObject.getString("main");
Log.d("MainService:", MainService);
String sub = jsonObject.getString("sub");
Log.d("sub:", sub);
SubList = new ArrayList<SubArray_method>();
JSONArray SubArray = jsonObject.getJSONArray("sub");
for (int j = 0; j < SubArray.length(); j++) {
/*JSONObject subjsonObject = SubArray.getJSONObject(j);*/
/*String SubServiceId = subjsonObject.getString("iSubServiceId");
Log.d("subserviceid:", SubServiceId);
String SubServiceName = subjsonObject.getString("vName");
Log.d("SubServiceName:", SubServiceName);
String SubServicePrice = subjsonObject.getString("fPrice");
Log.d("SubServicePrice:", SubServicePrice);
String SubServiceTime = subjsonObject.getString("vDuration");
Log.d("SubServiceTime:", SubServiceTime);*/
SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
SubArray.getJSONObject(j).getString("vName"),
SubArray.getJSONObject(j).getString("fPrice"),
SubArray.getJSONObject(j).getString("vDuration")));
}
// This should be in outer for loop<<---------------------<<<<<
MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
MainArray.getJSONObject(i).getString("main")));
}

Image duplicates in custom listview on scrolling

Whenever I am trying to remove an object from JsonArray , It shows there is no such method exists. My target API version is 8. I look up for other questions regarding this but could not find a suitable solution. please help me with this.
class JSONAsync extends AsyncTask<String, Void, JSONArray>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = Util.setProgressDialog(Activity.this, "Please Wait",
"loading....", false);
progressDialog.show();
}
#Override
protected JSONArray doInBackground(String... urls)
{
try
{
HttpGet httppost = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200)
{
HttpEntity entity = response.getEntity();
String resString = EntityUtils.toString(entity);
JSONObject jso= new JSONObject(resString);
JSONArray jsono= jso.getJSONArray("jobmasterto");
Log.e("jason array is this", ""+jsono);
for (int i = 0; i < jsono.length(); i++) {
if (jsono.getJSONObject(i).getString("jobName").equals(null) || jsono.getJSONObject(i).getString("jobName").equals("null") || jsono.getJSONObject(i).getString("jobName").equals("")) {
Log.e("Output : : ", jsono.getJSONObject(i).getString("jobName"));
jsono.remove(i);
}
}
if(jsono.length()>=0)
{
jobname = new String[(jsono.length())];
jobid = new String[(jsono.length())];
for(int i=0;i<jsono.length();i++)
{
JSONObject js = jsono.getJSONObject(i);
Log.e("Name : ", jsono.getJSONObject(i).getString("jobName"));
jobname[i] = jsono.getJSONObject(i).getString("jobName");
Log.e("Id : ", jsono.getJSONObject(i).getString("jobId"));
jobid[i] = jsono.getJSONObject(i).getString("jobId");
}
return jsono;
}
else
{
Toast.makeText(getApplicationContext(), "No Workers available : "+ logedinUserId , Toast.LENGTH_LONG).show();
return null;
}
}
} catch (IOException e)
{
e.printStackTrace();
} catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONArray result)
{
progressDialog.dismiss();
}
}
Do you really want a headache supporting a bit amount of so old devices?
Nevertheless, use this:
JSONObject jso= new JSONObject(resString);
JSONArray jsonArray = jso.getJSONArray("jobmasterto");
Log.e("jason array is this", ""+jsonArray);
ArrayList<Integer> i_ar = new ArrayList<Integer>();
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.getJSONObject(i).getString("jobName").equals(null) || jsonArray.getJSONObject(i).getString("jobName").equals("null") || jsonArray.getJSONObject(i).getString("jobName").equals("")) {
Log.e("Output : : ", jsonArray.getJSONObject(i).getString("jobName"));
i_ar.add(i);
}
}
JSONArray jsono = new JSONArray();
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i_ar.indexOf(i) == -1)
{
list.put(jsonArray.get(i));
}
}
}
if(jsono.length()>=0)
{
//.... continue...

Progress Bar not visible with Stand alone asynctask

I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}

how do i send all my json parsed data from one activity to another activity with intents

In my application after parsing json data i want to send the data from one activity to another activity with the help of intents. but in my second activity it shows only last array json data. it is not showing all the json parsed data in second activity.
first activity:
private class GetData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SearchActivity.this, "", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("FromCityid",fromcity_bus));
nameValuePair.add(new BasicNameValuePair("Tocityid",tocity_bus));
nameValuePair.add(new BasicNameValuePair("DOJ",journey_bus));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
// Log.v("TAG_RESULT",""+result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("Response");
String message = jobj.getString("Message");
String issuceess = jobj.getString("IsSuccess");
Log.v("TAG_Message",""+message);
Log.v("TAG_Message",""+issuceess);
if(issuceess.equals("true"))
{
JSONArray routearray = result.getJSONArray("Route");
for(int i = 0; i<routearray.length(); i++)
{
companyid = routearray.getJSONObject(i).getString("CompanyId");
CompanyName = routearray.getJSONObject(i).getString("CompanyName");
deptime = routearray.getJSONObject(i).getString("DepTime");
routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
arrtime =routearray.getJSONObject(i).getString("ArrTime");
fare =routearray.getJSONObject(i).getString("Fare");
hasac = routearray.getJSONObject(i).getString("HasAC");
hasnac = routearray.getJSONObject(i).getString("HasNAC");
hasseater = routearray.getJSONObject(i).getString("HasSeater");
hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
buslabel = routearray.getJSONObject(i).getString( "BusLabel");
avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
bustypename = routearray.getJSONObject(i).getString("BusTypeName");
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
intent.putExtra("COMPANYNAME", CompanyName);
Log.v("TAG_COMPANYNAME",""+CompanyName);
intent.putExtra("COMPANYID", companyid);
intent.putExtra("BUSFARE", fare);
intent.putExtra("BUSLABEL", buslabel);
intent.putExtra("BUSTYPENAME", bustypename);
intent.putExtra("AVALIABLESEATS", avaliableseats);
// intent.putExtra("arrayListIdentifier",);
startActivity(intent);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
secondActivity:
Intent intent = getIntent();
String company_name = intent.getStringExtra("COMPANYNAME");
String company_id = intent.getStringExtra("COMPANYID");
String bus_fare = intent.getStringExtra("BUSFARE");
String bus_typename = intent.getStringExtra("BUSTYPENAME");
String bus_label = intent.getStringExtra("BUSLABEL");
String avaliable_seats = intent.getStringExtra("AVALIABLESEATS");
BusData bs = new BusData();
bs.setCompanyname(company_name);
bs.setCompanyid(company_id);
bs.setFare(bus_fare);
bs.setBuslabel(bus_label);
bs.setBustypename(bus_typename);
bs.setAvaliableseats(avaliable_seats);
bdata.add(bs);
BusDataAdapter adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
fromto is a listview.
the size of bdata is 1.
Use Bundle to pass the value from current activity to next acivity
Current Activtiy to pass data
if(issuceess.equals("true"))
{
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
intent.putExtra("json_objcet", result.toString());//result is a json object
startActivity(intent);
}
In Next activity to receive data
Intent intent = getIntent();
String json_object = intent.getStringExtra("json_objcet");
try
{
JSONObject result = new JSONObject(json_object);
JSONArray routearray = result.getJSONArray("Route");
for (int i = 0; i < routearray.length(); i++) {
String companyid = routearray.getJSONObject(i).getString("CompanyId");
String CompanyName = routearray.getJSONObject(i).getString("CompanyName");
String deptime = routearray.getJSONObject(i).getString("DepTime");
String routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
String arrtime = routearray.getJSONObject(i).getString("ArrTime");
String fare = routearray.getJSONObject(i).getString("Fare");
String hasac = routearray.getJSONObject(i).getString("HasAC");
String hasnac = routearray.getJSONObject(i).getString("HasNAC");
String hasseater = routearray.getJSONObject(i).getString("HasSeater");
String hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
String isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
String buslabel = routearray.getJSONObject(i).getString("BusLabel");
String avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
String bustypename = routearray.getJSONObject(i).getString("BusTypeName");
BusData bs = new BusData();
bs.setCompanyname(CompanyName);
bs.setCompanyid(companyid);
bs.setFare(fare);
bs.setBuslabel(buslabel);
bs.setBustypename(bustypename);
bs.setAvaliableseats(avaliableseats);
bdata.add(bs);
}
BusDataAdapter adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
try this code
first activity
private class GetData extends AsyncTask<String, Void, JSONObject> {
ArrayList<BusData> arrayBusData = new ArrayList<BusData>();
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SearchActivity.this, "", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("FromCityid",fromcity_bus));
nameValuePair.add(new BasicNameValuePair("Tocityid",tocity_bus));
nameValuePair.add(new BasicNameValuePair("DOJ",journey_bus));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
// Log.v("TAG_RESULT",""+result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("Response");
String message = jobj.getString("Message");
String issuceess = jobj.getString("IsSuccess");
Log.v("TAG_Message",""+message);
Log.v("TAG_Message",""+issuceess);
if(issuceess.equals("true"))
{
JSONArray routearray = result.getJSONArray("Route");
for(int i = 0; i<routearray.length(); i++)
{
companyid = routearray.getJSONObject(i).getString("CompanyId");
CompanyName = routearray.getJSONObject(i).getString("CompanyName");
deptime = routearray.getJSONObject(i).getString("DepTime");
routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
arrtime =routearray.getJSONObject(i).getString("ArrTime");
fare =routearray.getJSONObject(i).getString("Fare");
hasac = routearray.getJSONObject(i).getString("HasAC");
hasnac = routearray.getJSONObject(i).getString("HasNAC");
hasseater = routearray.getJSONObject(i).getString("HasSeater");
hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
buslabel = routearray.getJSONObject(i).getString( "BusLabel");
avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
bustypename = routearray.getJSONObject(i).getString("BusTypeName");
BusData bData = new BusData(companyid,CompanyName,fare,buslabel,bustypename,avaliableseats,);
arrayBusData.add(bData);
}
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("bus_data", arrayBusData);
intent.putExtras(bundleObject);
startActivity(intent);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
second activity
ArrayList<BusData> arrayBusData = new ArrayList<BusData>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle bundleObject = getIntent().getExtras();
arrayBusData = (ArrayList<BusData>) bundleObject
.getSerializable("requestProductItem");
BusDataAdapter adapter = new BusDataAdapter(this, arrayBusData);
fromto.setAdapter(adapter);
}
BusData class also create constructor in BusData class
public class BusData implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;

Update Android Listview after Asynchronous update

I am converting my HTTP calls to asynchronous calls from synchronous ones. Because the connection is running in the background the data isn't there when I originally set my list adaptor. How can I get the list adaptor to update after my HTTP call? I've tried a few things like not setting the adaptor until data gets sent back and setting the adaptor again, but nothing has worked. Here's my current oncreate code
protected void onCreate(Bundle savedInstanceState) {
overridePendingTransition(R.layout.anim_out,R.layout.anim_in);
setTheme(R.style.Theme_D_theme);
setContentView(R.layout.news_fragment);
super.onCreate(savedInstanceState);
text = (TextView) this.findViewById(R.id.nomore);
list = (ListView) this.findViewById(R.id.newslist);
list.setDividerHeight(2);
new MyAsyncTask().execute("THIS");
list.setOnItemClickListener(this);
list.setCacheColorHint(Color.WHITE);
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
}
And my AsyncTast
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}
in on post execution add this line. in the end.
x.add(temp);
adapter.notifyDataSetChanged();
Do this way
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
//UPDATE HERE
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
list.setAdapter(adapter);
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}

Categories

Resources