I have two asynctask in one class and i am having trouble in executing them at the same time.
Here is my scenario, my the user clicks the view january calendar button it will show up the events for the month of calendar and the comments for it. The events and comments are stored in mysql database so i have to fetch different url. I used asyctask to fetch the url. Whenever i call the other asynctask it cannot be resolved. help me out!
Here is my code:
package sscr.stag;
#SuppressLint("ShowToast")
public class Calendar extends ListActivity {
// All xml labels
TextView txtEvent;
// Progress Dialog
private ProgressDialog pDialog;
JSONArray user;
JSONObject hay;
private static final String CALENDAR_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryCalendar.php";
private static final String COMMENT_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryReadComment.php";
private static final String TAG_USER = "username";
private static final String TAG_MESSAGE = "message";
private static final String TAG_TIME = "time";
private static final String TAG_ARRAY = "posts";
private JSONArray mCalendar = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendaradmin);
txtEvent = (TextView) findViewById(R.id.event);
new LoadCalendar().execute();
new LoadCommentCal().execute(); // error here, says cannot be resolved in this type
}
private class LoadCalendar extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Calendar.. ");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String json = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(CALENDAR_URL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(COMMENT_URL);
try {
mCalendar = json.getJSONArray(TAG_ARRAY);
for (int i = 0; i < mCalendar.length(); i++) {
JSONObject c = mCalendar.getJSONObject(i);
String username = c.getString(TAG_USER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, username);
mCommentList.add(0, map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(Calendar.this, mCommentList,
R.layout.calendar_comment, new String[] { TAG_MESSAGE,
TAG_USER, TAG_TIME }, new int[] { R.id.message,
R.id.username, R.id.time });
setListAdapter(adapter);
ListView lv = getListView();
lv.scrollTo(0, 0);
}
public class LoadCommentCal extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void... args) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
}
Your second asynctask public class LoadCommentCal extends AsyncTask is inside the first asynctask!
You need to move it out of the first asynctask.
private class LoadCalendar extends AsyncTask<String, String, String> {
...
}
... other functions
private class LoadCommentCal extends AsyncTask<Void, Void, String> {
...
}
You are declaring lots of things inside the first AsyncTask I strongly reccomend to close your AsyncTask after the onPostExecute
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
and then removing one } at the end of the java file (and also reindent if you wish)
Related
I have a json in which i have product_id and product_name through the Json products are showing in listview now i want that when clicked on item then id of that product should be show in toast. I am new to android i am unable to do this
can anyone tell me how can i do this please
public class CityNameActivity extends ListActivity{
ListView list;
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(),
Specialities_Activity.class);
startActivity(in);}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
Code of Service Handlerclass:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
code of Hospital Activity in which hospital is showing in listview i want that not all hospitals show only show hospital of specific city
public class HospitalList_Activity extends ListActivity {
private ProgressDialog pDialog;
// URL to get Hospitals JSON
private static String url = "http://14.140.200.186/hospital/get_hospital.php";
// JSON Node names
private static final String TAG_HOSPITAL = "Hospitals";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "hospital_name";
// Hospitals JSONArray
JSONArray Hospitals = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> hospitallist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_list_);
ListView listView=getListView();
hospitallist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), Specialities_Activity.class);
startActivity(in);
}
});
new GetHospitals().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetHospitals extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(HospitalList_Activity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Hospitals = jsonObj.getJSONArray(TAG_HOSPITAL);
// looping through All Cities
for (int i = 0; i < Hospitals.length(); i++) {
JSONObject c = Hospitals.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Hospitals = new HashMap<String, String>();
Hospitals.put(TAG_NAME, name);
// adding contact to Cities list
hospitallist.add(Hospitals);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(HospitalList_Activity.this, hospitallist, R.layout.hospital_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
public class CityNameActivity extends ListActivity {
ListView list;
Map <String, String> cityListWithId = new HashMap<String, String>();
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
private static final String TAG_ID = "city_id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String tagname = ((TextView) findViewById(R.id.name)).getText().toString();
Map<String, String> tempHashmap = (Map<String, String>) parent.getItemAtPosition(position);
String tagName = tempHashmap.get(TAG_NAME);
System.out.println("tagname" + tagName);
String tagId = (String)cityListWithId.get(tagName);
System.out.println("tagId" + tagId);
Toast.makeText(CityNameActivity.this, tagId,Toast.LENGTH_SHORT).show();
}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
cityListWithId.put(c.getString(TAG_NAME), c.getString(TAG_ID));
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
}
On ItemClick() method you can add this to get the id of the product.
HashMap<String,String> data = cityList.get(position);
//position is the paramater from ItemClick
String id = data.get("your key for Id");
why you every time hit the service . as per my opinion don't call service in onItemClick . when you start activity or app start Async task and pass data to list view .
please find below code . i am just refactor few thing so please let me if there some thing wrong
public class CityNameActivity extends ListActivity
{
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GetCities().execute();
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(citylist!=null && !citylist.isEmpty())
{
Toast.makeText(CityNameActivity.this,""+citylist.get(position).get(TAG_NAME).toString(),Toast.LENGTH_SHORT).show();
}
}
});
new GetCities().execute();
}
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
}
I have a JSON data from YouTube. I want to show data in LIST VIEW. But when i run my code I get a blank page. But I have the respond of YouTube DATA API. How can I solve it?
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA";
private static final String TAG_ITEMS = "items";
private static final String TAG_ID = "id";
private static final String TAG_ID_VIDEOID = "vid";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String YouTubeThumbnail = "https://i.ytimg.com/vi/hlaX2OZ_kDg/default.jpg";
private static final String TAG_CHANNELTITLE = "channelTitle";
JSONArray items = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String vid = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String title = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID_VIDEOID, vid);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
int count = 0;
try {
JSONObject js = new JSONObject(jsonStr);
JSONArray jsItem = js.getJSONArray("items");
for (int i = 0; i < jsItem.length(); i++) {
JSONObject item = jsItem.getJSONObject(i);
JSONObject vid =item.getJSONObject("id");
String videoId = getStringResult(vid.toString(), "videoId");
if (!videoId.equalsIgnoreCase(""))
{
JSONObject snippet =item.getJSONObject("snippet");
String title = sh.getStringResult(snippet.toString(), "title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", title);
map.put("vid", videoId);
map.put ("img","http://img.youtube.com/vi/" + videoId + "/hqdefault.jpg");
map.put ("id",++count+"");
dataList.add(map);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
public String getStringResult(String data, String node) {
try {
JSONObject js = new JSONObject(data);
return js.getString(node);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
Use notifyDataSetChanged(). This notifies a change in data and updated the list view. LINK
Here are the changes that would help:
public class MainActivity extends ListActivity {
...
ListAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
...
ListView lv = getListView();
adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
lv.setListAdapter(adapter);
...
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
...
}
#Override
protected Boolean doInBackground(Void... arg0) {
...
}
#Override
protected void onPostExecute(Boolean result) {
if(adapter ! = null) {
adapter.notifyDataSetChanged();
}
}
public String getStringResult(String data, String node) {
...
}
Explanation:
ListAdapter is the bridge between a ListView and the data that backs the list.
Whenever the data is changed, adapter is responsible to notify about the changed data and consequently the view gets updated with the new data. This is achieved by notifyDataSetChanged().
For some more details, please go through this link.
My app gets data from server and saves to sqlite using asyntask, but if there is slow or no internet connectivity the progress dialog never finishes and keeps searching for the internet.My app also runs the service for uploading the records to the server so i don't want to use another timer in the code. Please suggest me any solution.
public class DoctorsCallPlannigOperation extends AsyncTask<String, Void, String> {
ProgressDialog pd;
Context cxt;
public static List<String> listplannum;
public static List<String> listrefnum;
public static List<String> listcreateddate;
public static List<String> listdrcode;
public static List<String> listplandate;
public static List<String> listffmgr;
public static List<String> listffcode;
public static List<String> listmon;
public static List<String> listterrcode;
public static List<String> listmorn_even;
public static String tmp,TerrCode;
// String Response = "{\"Successful\":true}";
public DoctorsCallPlannigOperation(Context context,String terrcode) {
// TODO Auto-generated constructor stub
cxt = context;
pd = new ProgressDialog(context);
pd.setTitle("Please wait");
pd.setMessage("Loading...");
pd.setCancelable(false);
cxt= context;
TerrCode=terrcode;
}
#Override
protected String doInBackground(String... urls) {
RestAPI restAPI = new RestAPI();
JSONObject jsonObj = new JSONObject();
try {
jsonObj = restAPI.getDocCallsPlanning(TerrCode);
tmp = jsonObj.toString();
JSONObject jo = new JSONObject(tmp);
JSONArray ja = jo.getJSONArray("Value");
listplannum = new ArrayList<String>();
listrefnum = new ArrayList<String>();
listcreateddate = new ArrayList<String>();
listdrcode = new ArrayList<String>();
listplandate = new ArrayList<String>();
listffmgr = new ArrayList<String>();
listffcode = new ArrayList<String>();
listmon = new ArrayList<String>();
listterrcode = new ArrayList<String>();
listmorn_even = new ArrayList<String>();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
listplannum.add(jo.getString("PLAN_NO"));
listrefnum.add(jo.getString("REF_NO"));
listcreateddate.add(jo.getString("CREATED_DATE"));
listdrcode.add(jo.getString("DR_CODE"));
listplandate.add(jo.getString("PLAN_DATE"));
listffmgr.add(jo.getString("FF_MGR"));
listffcode.add(jo.getString("FF_CODE"));
listmon.add(jo.getString("MON"));
listterrcode.add(jo.getString("TERR_CODE"));
listmorn_even.add(jo.getString("MORN_EVEN"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncGetSpecialities", e.getMessage());
}
return tmp;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.show();
}
}
This need to be in onPreExecute:
pd = new ProgressDialog(context);
pd.setTitle("Please wait");
pd.setMessage("Loading...");
pd.setCancelable(false);
pd.show();
And this need to be in onPostExecute:
if(pd != null)
pd.dismiss();
In my application I used autocompletetextview to retrieve data,the data which I display is using json,now autocompletetextview works well,but what I want is after getting name in my autocompletetextview I want to send id of category,but it sends name..following is my response..and my snippet code is here..Autocompletetextview not working
{
"category":
[
{
"id":"4",
"name":"cat1"
},
{
"id":"7",
"name":"aditya"}
]
}
Add_Catagory.java
public class MainActivity extends Activity {
private Button btns;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private MultiAutoCompleteTextView acTextView;
private static final String FEEDBACK_URL = "";
private static final String FEEDBACK_SUCCESS = "status";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acTextView = (MultiAutoCompleteTextView) findViewById(R.id.autoComplete);
acTextView.setAdapter(new SuggestionAdapter(this,acTextView.getText().toString()));
acTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
/* JsonParse jp=new JsonParse();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
list.get(0).getId();*/
btns=(Button)findViewById(R.id.btn);
btns.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
});
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
private String catid;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Sending..");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String pweighttype=acTextView.getText().toString();
try {
JsonParse jp=new JsonParse();
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.size();i++){
if(list.get(i).getName().equals(acTextView.getText().toString()))
params.add(new BasicNameValuePair("parentid",list.get(i).getId()));
System.out.println("Su gayu server ma"+params);
catid=list.get(i).getId().toString();
}
System.out.println("Su catid"+catid);
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
FEEDBACK_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(FEEDBACK_SUCCESS);
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
//parentcat.getText().clear();
}}
try this//modify doInBackground
try {
JsonParse jp=new JsonParse();
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.length();i++){
if(list.get(i).getName().equals(acTextView.getText().toString()))
params.add(new BasicNameValuePair("parentid",list.get(i).getId()));
break;
}
I'm doing an app that has mutiple tab and for each tab has its own activity. after putting the code to load the list on one activity; still listview is not visible at all.
here is my code, somebody please help:
public class BillsActivity extends ListActivity {
private ProgressDialog pDialog;
String mUrl = BayadCenterConstants.BAYAD_URL_BILLERS;
JSONParsers jsonParser = new JSONParsers();
ArrayList<HashMap<String, String>> billerList;
JSONArray billers = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_child_bills);
/*
* Check network connection here
*/
billerList = new ArrayList<HashMap<String, String>>();
new LoadBillers().execute();
}
class LoadBillers extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(BillsActivity.this);
pDialog.setMessage("Downlaoding list ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String json = jsonParser.getBillers(mUrl, params);
Log.d("Billers JSON: ", "> " + json);
try {
billers = new JSONArray(json);
if (billers != null) {
for (int i = 0; i < billers.length(); i++) {
JSONObject c = billers.getJSONObject(i);
String id = c.getString("bid");
String name = c.getString("name");
String status = c.getString("status");
String date_added = c.getString("date_added");
HashMap<String, String> map = new HashMap<String, String>();
map.put("bid", id);
map.put("name", name);
map.put("status", status);
map.put("date_added", date_added);
billerList.add(map);
}
}else{
Log.d("Billers: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
BillsActivity.this, billerList,
R.layout.tab_child_bills_list_row, new String[] { "bid", "name", "status",
"date_added" }, new int[] { R.id.txtBillerID, R.id.txtBillerName,
R.id.txtBillerStatus, R.id.txtBillerDateAdded });
setListAdapter(adapter);
}
});
}
}
this activity is just part of an activity that holds then in tab+swipe manner.
did i miss something with my code?