Related
I am new in android,I have one application,in my application i am getting user's profile data,here in my profile data i am getting user's state and city which user had previously set,like right now user set following state and city,and i am able to display that state and city in my spinner
{
"user_city": "Kolkata",
"user_state": "West Bengal",
}
Now issue is if user want to change state like from WestBengal to Karnataka,then i need to display all state and make user to change,so for that i have other separate webservice for load all state and i want to display that all state in same that spinner,but right now issue is i need to click two times then only it is showing all states
this is the response
[{"user_status":"1","state_id":"1","state":"Karnataka"},{"user_status":"1","state_id":"2","state":"Tamilnadu"},{"user_status":"1","state_id":"3","state":"Maharastra"},{"user_status":"1","state_id":"4","state":"Andhra Pradesh"},{"user_status":"1","state_id":"5","state":"West Bengal"},{"user_status":"1","state_id":"6","state":"Delhi"},{"user_status":"1","state_id":"8","state":"Andaman & Nicobar Islands"},{"user_status":"1","state_id":"9","state":"Arunachal Pradesh"},{"user_status":"1","state_id":"10","state":"Bihar"},{"user_status":"1","state_id":"11","state":"Chattisgarh"},{"user_status":"1","state_id":"12","state":"Dadra & Nagar Haveli"},{"user_status":"1","state_id":"13","state":"Daman & Diu"},{"user_status":"1","state_id":"14","state":"Goa"},{"user_status":"1","state_id":"15","state":"Gujarat"},{"user_status":"1","state_id":"16","state":"Haryana"},{"user_status":"1","state_id":"17","state":"Himachal Pradesh"},{"user_status":"1","state_id":"18","state":"Jharkhand"},{"user_status":"1","state_id":"19","state":"Kerala"},{"user_status":"1","state_id":"20","state":"Lakshadweep"},{"user_status":"1","state_id":"21","state":"Madhya pradesh"},{"user_status":"1","state_id":"22","state":"Pondichery"},{"user_status":"1","state_id":"23","state":"Punjab"},{"user_status":"1","state_id":"24","state":"Rajasthan"},{"user_status":"1","state_id":"25","state":"Sikkim"},{"user_status":"1","state_id":"26","state":"Telangana"},{"user_status":"1","state_id":"27","state":"Tripura"},{"user_status":"1","state_id":"28","state":"Uttaranchal"},{"user_status":"1","state_id":"29","state":"Uttar Pradesh"},{"user_status":"1","state_id":"31","state":"Nagaland"},{"user_status":"1","state_id":"32","state":"Mizoram"},{"user_status":"1","state_id":"33","state":"Meghalaya"},{"user_status":"1","state_id":"34","state":"Manipur"},{"user_status":"1","state_id":"35","state":"Assam"},{"user_status":"1","state_id":"36","state":"Chandigarh"},{"user_status":"1","state_id":"37","state":"Orissa"},{"user_status":"1","state_id":"38","state":"Others"}]
Loading profile
class LoadAllProdetails extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
private String test;
private JSONObject jsonObjsss;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profiles.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(GET_PRO_DETAILS, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObjsss = new JSONObject(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
profilessstates=new ArrayList<HashMap<String,String>>();
profilecitis=new ArrayList<HashMap<String,String>>();
if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("0"))
{
final String msgs=jsonObjsss.getString("message");
System.out.println("Messagessss"+msgs);
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getActivity(), msgs, Toast.LENGTH_LONG).show();
}
});
}
else if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("1")) {
HashMap<String, String> mapzz = new HashMap<String, String>();
usersstatus = jsonObjsss.getString(GET_PRO_USERSTATUS);
usersfname = jsonObjsss.getString(GET_PRO_FIRSTNAME);
usersmails = jsonObjsss.getString(GET_PRO_EMAILS);
usersmob = jsonObjsss.getString(GET_PRO_MOBILE);
usersdobs = jsonObjsss.getString(GET_PRO_DATES);
usersaddresss = jsonObjsss.getString(GET_PRO_ADDRESS);
userszipss = jsonObjsss.getString(GET_PRO_ZIP);
userstates=jsonObjsss.getString(GET_PRO_STATE);
usercitys=jsonObjsss.getString(GET_PRO_CITY);
mapzz.put(GET_PRO_STATE, jsonObjsss.getString(GET_PRO_STATE));
mapzz.put(GET_PRO_CITY, jsonObjsss.getString(GET_PRO_CITY));
profilessstates.add(mapzz);
profilecitis.add(mapzz);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return profilessstates;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
updtfname.setText(usersfname);
updtmail.setText(usersmails);
updtmob.setText(usersmob);
updtaddress.setText(usersaddresss);
updtpin.setText(userszipss);
datestext.setText(usersdobs);
arrprostates = new String[profilessstates.size()];
for (int index = 0; index < profilessstates.size(); index++) {
HashMap<String, String> map = profilessstates.get(index);
arrprostates[index] = map.get(GET_PRO_STATE);
}
adapterprostates = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrprostates);
statespinner.setAdapter(adapterprostates);
arrprocities = new String[profilecitis.size()];
for (int index = 0; index < profilecitis.size(); index++) {
HashMap<String, String> map = profilecitis.get(index);
arrprocities[index] = map.get(GET_PRO_CITY);
}
adapterprocities = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrprocities);
cityspinner.setAdapter(adapterprocities);
To load all states
class LoadStatess extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
private String test;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profiles.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
statedata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(USER_STATUSS, c.getString(USER_STATUSS));
map.put(PRESET_TITLES, c.getString(PRESET_TITLES));
statedata.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return statedata;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
// pDialog.dismiss();
arrallstates = new String[statedata.size()];
for (int index = 0; index < statedata.size(); index++) {
HashMap<String, String> map = statedata.get(index);
arrallstates[index] = map.get(PRESET_TITLES);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adapterallstates = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrallstates);
statespinner.setAdapter(adapterallstates);
statespinner.setPrompt("Select State");
statespinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spitems = statespinner.getSelectedItem().toString();
System.out.println("PresetEVent selected" + spitems);
new Logincity().execute();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
first screen by default get
then i click to load state it shows
then again i click the only it shows
Put these lines in OnCreate method of your activity.
adapterallstates = new ArrayAdapter<String>(Profiles.this.getActivity(),android.R.layout.simple_spinner_dropdown_item, new ArrayList<String>());
statespinner.setAdapter(adapterallstates);
And delete these lines from onPostExecute:
adapterallstates = new ArrayAdapter<String>(Profiles.this.getActivity(),android.R.layout.simple_spinner_dropdown_item, arrallstates);
statespinner.setAdapter(adapterallstates);
And add these lines in for loop of onPostExecute.
adapterallstates.add(map.get(PRESET_TITLES));
adapterprostates.notifyDataSetChanged();
Do this it will work for you.
other one is to,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoadListView();
}
private void LoadListView() {
try {
statespinner.setAdapter(adapterprostates);
} catch (Exception e) {
e.printStacktrace();
}
}
I have a paginated JSON file where I have all my data. At the end of my url link, if you change the page number, it executes and lists next items like "?page=1" or "3,4,5,6".
By default its kept at "?page=0" which is the first page viewed when parsed in Android.
I have also added a footer view with a Button "LoadMore" which is seen at the end of the listview.
Now I wanted this LoadMore button to go to page 2 after clicking when I am at page 1 end. again to page 3, when I click LoadMore on page 2.
I am so confused of implementing it. This is my Asynic Task. Something to do in "doInBackground"
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
current_page = 0;
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=" + current_page;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(),RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name = ((TextView)
view.findViewById(R.id.restaurant_name)).getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
This is my LoadMore Button code.
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
My searchAll file, where all the code goes.
public class SearchAll extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
//Progress Dialog
private ProgressDialog pDialog;
//make json parser Object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> restaurant_list;
//Restaurant Json array
JSONArray restaurants = null;
private String URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//all JSON Node Names
private static final String TAG_ID = "login_id";
private static final String TAG_NAME = "name";
private static final String TAG_LOCATION = "location";
private static final String TAG_RATING = "rating";
//Flag for current page
int current_page = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_all);
cd = new ConnectionDetector(getApplicationContext());
//Check for Internet Connection
if (!cd.isConnectingToInternet()) {
//Internet connection not present
alert.showAlertDialog(SearchAll.this, "Internet Connection Error",
"Please Check Your Internet Connection", false);
//stop executing code by return
return;
}
restaurant_list = new ArrayList<HashMap<String, String>>();
new LoadRestaurants().execute();
//new LoadRestaurants().execute();
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new LoadMore().execute();
}
});
}
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name =((TextView) view.findViewById
(R.id.restaurant_name)).
getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
private class LoadMore extends AsyncTask<Void, Void, Void> {
//Show Progress Dialog
#Override
protected Void doInBackground(Void... voids) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
current_page = current_page + 1;
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=" + current_page;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
}
Finally got it working!
public class SearchAll extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
//Progress Dialog
private ProgressDialog pDialog;
//make json parser Object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> restaurant_list;
//Restaurant Json array
JSONArray restaurants = null;
private String URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//all JSON Node Names
private static final String TAG_ID = "login_id";
private static final String TAG_NAME = "name";
private static final String TAG_LOCATION = "location";
private static final String TAG_RATING = "rating";
//Flag for current page
// int current_page = 1;
int bCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_all);
cd = new ConnectionDetector(getApplicationContext());
//Check for Internet Connection
if (!cd.isConnectingToInternet()) {
//Internet connection not present
alert.showAlertDialog(SearchAll.this, "Internet Connection Error",
"Please Check Your Internet Connection", false);
//stop executing code by return
return;
}
restaurant_list = new ArrayList<HashMap<String, String>>();
new LoadRestaurants().execute();
//new LoadRestaurants().execute();
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bCount++;
new LoadRestaurants().execute();
}
});
}
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android /allRestaurantList3.php?page=
" + bCount;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name = ((TextView) view.findViewById(R.id.restaurant_name))
.getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
}
I'm fresher to android. I created android ListView using JSON WebService. I want old ListView data to be clear and reset again new data when getdata button is clicked again . Help me, thanks in advance.
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
JobNo =(EditText)findViewById(R.id.editText1);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.clear();
params.add(new BasicNameValuePair("JobNo",JobNo.getText().toString()));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
if (JobNo.getText().toString().equals(""))
{
Toast.makeText(MainActivity.this, "You did not enter a JobNo", Toast.LENGTH_SHORT).show();
}
else {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime); HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
Whenever you want to update your list clear the old data by
if(CargoTracklist != null){
CargoTracklist.clear();
// Add new Data to CargoTracklist
CargoTracklist.add("new data");
if(adapter != null){
adapter.notifyDataChaned();
}
}
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?
I have an EditText which takes a String from the user and a searchButton.
When the searchButton is clicked, it will search through the XML file and display it in the ListView.
I am able to take input from the user, search through the XML file and display the usersearched value in the ListView also.
What I want is to display a ProgressDialog after the searchButton is clicked like "PLEASE WAIT...RETRIEVING DATA..." or something like that and dismiss it when the data is shown.
public class Tab1Activity extends ListActivity {
private Button okButton;
private Button searchButton;
Toast toast;
String xml;
private TextView searchText;
private String searchTextString;
HashMap<String, String> o;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
searchButton = (Button) findViewById(R.id.search_button);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.print("hello");
searchText = (TextView) findViewById(R.id.search_text);
searchTextString = searchText.getText().toString();
readXml(searchTextString);
}
});
}
private void readXml(String searchTextString1) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
//Here XMLfunctions is class name which parse xml
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if ((numResults <= 0)) {
Toast.makeText(Tab1Activity.this, "Testing xmlparser",
Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
String nameMapString = XMLfunctions.getValue(e, "name");
if ( nameMapString.toLowerCase().indexOf(searchTextString1.toLowerCase()) != -1 ) // != -1 means string is present in the search string
{
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", XMLfunctions.getValue(e, "name"));
map.put("Score", XMLfunctions.getValue(e, "score"));
mylist.add(map);
}
}
ListAdapter adapter = new SimpleAdapter(this, mylist,
R.layout.parsexml, new String[] { "name", "Score" }, new int[] {
R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Toast.makeText(Tab1Activity.this,
"Name "+o.get("name")+" Clicked", Toast.LENGTH_LONG)
.show();
}
});
}
Declare your progress dialog:
ProgressDialog progress;
When you're ready to start the progress dialog:
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
and to make it go away when you're done:
progress.dismiss();
Here's a little thread example for you:
// Note: declare ProgressDialog progress as a field in your class.
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new Thread(new Runnable() {
#Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
#Override
public void run()
{
progress.dismiss();
}
});
}
}).start();
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
try {
String xmlUrl = urls[0];
URL u = new URL(xmlUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lengthOfFile = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; // total = total + len1
publishProgress("" + (int) ((total * 100) / lengthOfFile));
xmlContent += buffer;
}
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Retrieving latest announcements...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
While creating the object for the progressbar check the following.
This fails:
dialog = new ProgressDialog(getApplicationContext());
While adding the activities context works..
dialog = new ProgressDialog(MainActivity.this);
You should not execute resource intensive tasks in the main thread. It will make the UI unresponsive and you will get an ANR. It seems like you will be doing resource intensive stuff and want the user to see the ProgressDialog. You can take a look at http://developer.android.com/reference/android/os/AsyncTask.html to do resource intensive tasks. It also shows you how to use a ProgressDialog.
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
private class GetData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Calendar.this,
"", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
String status = jobj.getString("status");
if(status.equals("true"))
{
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", array.getJSONObject(x).getString("name"));
map.put("date", array.getJSONObject(x).getString("date"));
map.put("description", array.getJSONObject(x).getString("description"));
list.add(map);
}
CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);
list_of_calendar.setAdapter(adapter);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
and execute it in OnCreate Method like new GetData().execute();
where Calendar is my calendarActivity and i have also created a CalendarAdapter to set these values to a list view.