Problem is with the filter(Textwatcher) : My app, show 2 record when data matches the value present in the first name & 1 record when the record matches the value in lastname.
example: when I type M it will show 2 record for mary but when I type k it show 1 record of mary kom and 2 record of Karl plus json data(refer below json)
{
"details": [
{
"id": "01",
"name": "Mary Kom",
"email": "abc#uvw.in",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "02",
"name": "karl plus",
"email": "pqrp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]}
Code:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
EditText inputSearch;
ListAdapter adapter;
// URL to get contacts JSON
private static String url = "http://www.abcd.in/api/details";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Enabling Search Filter
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
// When user change the Text
((SimpleAdapter) adapter).getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence cs, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable cs) {
// TODO Auto-generated method stub
}
});
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((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_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#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 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
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} 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();
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item, new String[]
{ TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] { R.id.name,R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I think it is a default behavior of filter with SimpleAdapter. what you wants to achieve, you need to implement your own custom filter.
See the Example here :- http://www.androidbegin.com/tutorial/android-search-listview-using-filter/
Change this code :
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (WorldPopulation wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
to
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (WorldPopulation wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).startsWith(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
It help you to achieve functionality.
Related
Would really apreciate if someone can help me out here. Trying to get "full_name", "Sex" and "location" if "full_name" is "John" but not working
public class DataParser extends AsyncTask<Void,Void,Integer>{
Context c;
ListView lv;
String jsonData;
ProgressDialog pd;
ArrayList<Person> persons=new ArrayList<>();
public DataParser(Context c, ListView lv, String jsonData) {
this.c = c;
this.lv = lv;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing...Please wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
}else {
//CALL ADAPTER TO BIND DATA
CustomAdapter adapter=new CustomAdapter(c,persons);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try {
JSONObject ja= new JSONObject(jsonData);
persons.clear();
Person s=null;
JSONObject jo=ja.getJSONObject("full_name");
if (jo.equals("John")) {
int id = jo.getInt("id");
String name = jo.getString("full_name");
String sex = jo.getString("sex");
String location = jo.getString("location");
s = new Person();
s.setId(id);
s.setFull_name(name);
s.setSex(sex);
s.setLocation(location);
persons.add(s);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Would really apreciate if someone can help me out here. Trying to get "full_name", "Sex" and "location" if "full_name" is "John" but not working
I'm going to guess that you have a JSONArray of person and you want to get the object that has person = John.
If the data is like this
[{
"full_name": "John Smith",
"sex": "male",
"location": "New York, NY, United States"
}, {
"full_name": "Angela Johnson",
"sex": "female",
"location": "San Diego, CA, United States"
}]
You can write:
JSONArray people = new JSONArray(jsondata);
int index = 0;
for (int i = 0; i < people.length(); i++) {
JSONObject tmpObj = people.getJSONObject(i);
string name = tmpObj.getString("full_name");
if (name == "John") {
index = i;
break;
}
}
JSONObject johnObjExample = people.getJSONObject(index);
string johnName = johnObjExample.getString("full_name");
int id = johnObjExample.getInt("id");
String name = johnObjExample.getString("full_name");
String sex = johnObjExample.getString("sex");
String location = johnObjExample.getString("location");
Problems: in Textwatcher
search(filter) show 2 record when data matches the value present in the first name eq when I type M it will show 2 record for mary but when I type k it show 1 record of mary kom and 2 record of Karl plus
json data
{"details": [
{
"id": "01",
"name": "Mary Kom",
"email": "abc#uvw.in",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "02",
"name": "karl plus",
"email": "pqrp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]}
The code:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
EditText inputSearch;
ListAdapter adapter;
// URL to get contacts JSON
private static String url = "http://www.abcd.in/api/details";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Enabling Search Filter
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
// When user change the Text
((SimpleAdapter) adapter).getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence cs, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable cs) {
// TODO Auto-generated method stub
}
});
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((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_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#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 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
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} 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();
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(MainActivity.this, contactList, R.layout.list_item, new String[]
{ TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] { R.id.name,R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I am trying to create a ListView with a filter in Android.
We have two drop-downs, Role and Gender, and one Search button.
When a user clicks the Search button, I want to show data related to the selected drop down values only.
For example, if I select "Engineer" and "Male" from "Role" and "Gender" respectively, then it should only show data that have Engineer in "Role" and Male in "Gender".
From the following JSON file, the only record that should be shown is "BHARGAV".
{
"contacts": [
{
"id": "c200",
"name": "Bhargav",
"email": "ab#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"role" : "Engineer",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny",
"email": "johnny#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "female",
"role" : "CharteredAccountant",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c202",
"name": "Leonardo Dicaprio",
"email": "leonardo_dicaprio#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"role" : "Doctor",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]
}
This is my code
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.examplesite.com/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_ROLE = "role";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((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_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#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 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
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
String role = c.getString(TAG_ROLE);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} 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();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
It is not working as intended.
What is wrong? How can I implement this properly?
You can set if condition in for loop where you getting all datas from JSON and set in adapter like below...
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
if(c.getString(TAG_GENDER).equalsIgnoreCase((String) Role.getSelectedItem()) && c.getString(TAG_ROLE).equalsIgnoreCase((String) Gender.getSelectedItem())) {
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
String role = c.getString(TAG_ROLE);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
}
Once you fetch all the data from server and fill contactListlist then you need to compare your data with user given conditions.
simple iterate contactList and check for user given values
check below pseudo code
ArrayList<HashMap<String, String>> finalList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < contactList.length(); i++) {
HashMap<String, String> map = contactList.get(i);
if(map.TAG_NAME == "BHARGAV" && map.TAG_GENDER == "MALE"){
finalList.add(map);
}
now use this 'finalList' to display values
TIP : Its good to create a model/custom class to hold the data than Hashmap.
I have used json with my Listview in fragment but it take time because i have 190 object so i want it to show only 15 items of Json and will so 15 more if the user scroll to the end. My json file i got from dropbox the size is 2,3MB. Can any tell me a good suggestion ? Thank in advance.
Here are the code.
public class UniversityFragment extends Fragment implements OnScrollListener{
ListView lv;
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CityProvince = "city/province";
private static final String TAG_Country = "country";
private static final String TAG_PHONE_OFFICE = "officephone";
private static final String TAG_Fax = "fax";
private static final String TAG_EMAIL = "email";
private static final String TAG_Site = "site";
private static final String TAG_image = "image";
int textlength = 0;
// contacts JSONArray
JSONArray contacts = null;
JSONObject jsonobject;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
// Search EditText
EditText inputSearch;
public UniversityFragment() {
}
#SuppressLint("CutPasteId")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_university,
container, false);
// Execute DownloadJSON AsyncTask
contactList = new ArrayList<HashMap<String, String>>();
lv = (ListView) rootView.findViewById(R.id.listView1);
inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
lv.setTextFilterEnabled(true);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before,
int count) {
// TODO Auto-generated method stub
// When user changed the Text
// UniversityFragment.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence cs, int start,
int count, int after) {
// TODO Auto-generated method stub
try {
// ((Filterable)
// UniversityFragment.this.contacts).getFilter().filter(cs);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getActivity(), "" + e, Toast.LENGTH_SHORT)
.show();
}
// lv.setTextFilterEnabled(true);
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Clicked" + position,
Toast.LENGTH_LONG).show();
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cp = ((TextView) view.findViewById(R.id.CPt)).getText()
.toString();
String country = ((TextView) view.findViewById(R.id.countryt))
.getText().toString();
String fax = ((TextView) view.findViewById(R.id.faxt))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.sitet))
.getText().toString();
String email = ((TextView) view.findViewById(R.id.emailt))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phonet))
.getText().toString();
String address = ((TextView) view.findViewById(R.id.addresst))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity(), SingleListItem.class);
in.putExtra("email", email);
in.putExtra("city/province", cp);
in.putExtra("country", country);
in.putExtra("fax", fax);
in.putExtra("site", site);
in.putExtra("name", name);
in.putExtra("officephone", phone);
in.putExtra("address", address);enter code here
startActivity(in);
}
});
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0) {
}
}
});
// Calling async task to get json
new GetContacts().execute();
return rootView;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Loading");
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Create an array
contactList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String url = "https://dl.dropbox.com........";
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
enter code here
// Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String country = c.getString(TAG_Country);
String cityprovince = c.getString(TAG_CityProvince);
String officephone = c.getString(TAG_PHONE_OFFICE);
String fax = c.getString(TAG_Fax);
String email = c.getString(TAG_EMAIL);
String site = c.getString(TAG_Site);
// // Phone node is JSON Object
// JSONObject phone = c.getJSONObject(TAG_PHONE);
// String home = phone.getString(TAG_PHONE_HOME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_ADDRESS, address);
contact.put(TAG_CityProvince, cityprovince);
contact.put(TAG_Country, country);
contact.put(TAG_PHONE_OFFICE, officephone);
contact.put(TAG_EMAIL, email);
contact.put(TAG_Site, site);
contact.put(TAG_Fax, fax);
// adding contact to contact list
contactList.add(contact);
}
} 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) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
Toast.makeText(getActivity(), "Thank for your patience", Toast.LENGTH_LONG).show();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(), contactList,
R.layout.listsingleitem, new String[] { TAG_NAME,
TAG_ADDRESS, TAG_CityProvince, TAG_Country,
TAG_PHONE_OFFICE, TAG_Fax, TAG_EMAIL, TAG_Site },
new int[] { R.id.name, R.id.addresst, R.id.CPt,
R.id.countryt, R.id.phonet, R.id.faxt, R.id.emailt,
R.id.sitet });
adapter.notify();
//adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
You need to implement an endless adapter (custom listview adapter) to support loading and displaying concurrently.
See this tutorial: http://www.survivingwithandroid.com/2013/10/android-listview-endless-adapter.html
I was looking for a simple example on parsing a JSON file, using the loopj AsyncHttpClient. But so far I could not find any useful information. :(
Simple JSON file to parse:
{
"contact": [
{
"id": "10",
"name": "Tom",
"email": "tom#gmail.com"
}
}
]
}
I would be grateful for any suggestion.
Thanks!!
You need to get the json first. I assume you have done that
{ // json object node
"contact": [ //json array contact
{ // json object node
To parse
JSONObject jb = new JSONObject("your json");
JSONArray con = jb.getJSONArray("contact");
JSONObject contact = (JSONObject) con.getJSONObject(0);
String id = contact.getString("id");
String name = contact.getString("name");
String id = contact.getString("id");
public class MainActivity extends Activity {
private ProgressDialog pdialog;
private static String url = "http://highspecificationservers.com/apk/webservice.php";
private static final String TAG_STUDENT = "student";
private static final String TAG_FNAME = "fname";
private static final String TAG_EMAIL = "email";
private static final String TAG_MOBILE = "mobile";
JSONArray student = null;
ArrayList<HashMap<String, String>> studentlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentlist = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String fname = ((TextView) view.findViewById(R.id.fname))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_FNAME, fname);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_MOBILE, description);
startActivity(in);
}
});
new GetStudent().execute();
}
private class GetStudent extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(MainActivity.this);
pdialog.setMessage("please wait");
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
String jString = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response:", "> " + jString);
if (jString != null) {
try {
JSONObject Jsonobj = new JSONObject(jString);
student = Jsonobj.getJSONArray(TAG_STUDENT);
for (int i = 0; i < student.length(); i++) {
JSONObject c = student.getJSONObject(i);
String fname = c.getString(TAG_FNAME);
String email = c.getString(TAG_EMAIL);
String mobile = c.getString(TAG_MOBILE);
HashMap<String, String> student = new HashMap<String, String>();
student.put(TAG_FNAME, fname);
student.put(TAG_EMAIL, email);
student.put(TAG_MOBILE, mobile);
studentlist.add(student);
}
} 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) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pdialog.isShowing())
pdialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
studentlist, R.layout.list_item, new String[] { TAG_FNAME,
TAG_EMAIL, TAG_MOBILE }, new int[] { R.id.fname,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
Go with this...
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}