Im currently working on an online mobile app. i have a listview populated from the database. in my listview, im trying to filter the data from the inputted data in my edittext above my listview.But i have hard time working on search. Im using a custom arrayadapter for my listview but the listview is not being filtered. It shows the same data. Please anyone out there to help me fix my problem. thanks :)
heres my ListofCityAdapter.class
public class ListofCityAdapter extends ArrayAdapter implements Filterable{
int groupid;
ArrayList<City> records;
ArrayList<City> items;
Context context;
public ListofCityAdapter(Context context, int vg, int id, ArrayList<City> objects) {
super(context, vg, id, objects);
this.context = context;
groupid = vg;
this.records = objects;
} public int getCount() {
return records.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(groupid, parent, false);
TextView textName = (TextView) itemView.findViewById(R.id.city_name);
textName.setText(records.get(position).getCityName());
TextView cityregion = (TextView)itemView.findViewById(R.id.city_region);
cityregion.setText(records.get(position).getRegion());
ImageView image = (ImageView)itemView.findViewById(R.id.image);
//mage.setImageResource(R.drawable.progress);
new DownloadImageTask(image).execute(records.get(position).getImage());
return itemView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<City> results = new ArrayList<City>();
if (records == null)
records = items;
if (constraint != null) {
if (records != null && records.size() > 0) {
for (final City g : records) {
if (g.getCityName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
items = (ArrayList<City>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
and here's my ListOfCityPage.class
public class ListofCity extends Fragment implements AdapterView.OnItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
Spinner filter;
ListofCityAdapter cityAdapter;
GridView listCity;
ArrayList<City> list;
ArrayList<City> records;
int id;
// SharedPreferences.Editor citylist;
String line=null;
String filtering,cityname,text;
SwipeRefreshLayout swipeLayout;
View view;
public ListofCity(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_listof_city, container, false);
context = getActivity();
records = new ArrayList<City>();
listCity = (GridView) view.findViewById(R.id.cities);
cityAdapter = new ListofCityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
list = new ArrayList<City>();
filter = (Spinner) view.findViewById(R.id.filter);
String categories[] = getResources().getStringArray(R.array.filtering);
ArrayAdapter<String> cat = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories);
cat.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
filter.setAdapter(cat);
listCity.setTextFilterEnabled(true);
filter.setOnItemSelectedListener(this);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(), City_attractions.class);
Toast.makeText(getActivity(), "Opening", Toast.LENGTH_LONG).show();
cityname = records.get(position).getCityName();
String info = records.get(position).getDescription();
String area = records.get(position).getArea();
String population = records.get(position).getPopulation();
String region = records.get(position).getRegion();
String province = records.get(position).getProvince();
myIntent.putExtra("cityname", cityname);
myIntent.putExtra("cityinfo", info);
myIntent.putExtra("cityarea", area);
myIntent.putExtra("citypopulation", population);
myIntent.putExtra("cityregion", region);
myIntent.putExtra("cityprovince", province);
startActivity(myIntent);
}
});
final EditText search = (EditText)view.findViewById(R.id.inputSearch);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
text = search.getText().toString().toLowerCase(Locale.getDefault());
filter(text);
}
});
return view;
}
public void filter(String charText) {
charText = text.toLowerCase(Locale.getDefault());
list.clear();
if (charText.length() == 0) {
list.addAll(records);
} else {
for (City wp : records) {
if (wp.getCityName().toLowerCase(Locale.getDefault())
.contains(charText)) {
list.add(wp);
}
}
}
cityAdapter.notifyDataSetChanged();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
fetchCity fetch = new fetchCity();
switch (position){
case 0:
filtering ="All";
fetch.execute();
break;
case 1:
filtering ="Alphabetically";
fetch.execute();
break;
case 2:
filtering ="Region";
fetch.execute();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeLayout.setRefreshing(false);
new fetchCity().execute();
}
}, 5000);
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
/**
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
**/ }
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("filter", filtering));
try
{
records.clear();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getcity.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("cityName"));
p.setArea(json_data.getString("area"));
p.setPopulation(json_data.getString("population"));
p.setImage(json_data.getString("path"));
p.setDescription(json_data.getString("city_info"));
p.setProvince(json_data.getString("province"));
p.setRegion(json_data.getString("region"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
To filter a listView with EditText, the simplest way is to use a textwatcher. Use the onTextChanged method of the textwatcher rather than afterTextChanged. And i think you probably don't need the public void filter(xyz) method as well. This code will probably work for you:
inputText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
YouActivityName.this.cityAdapter.getFilter().filter(s);
cityAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
Related
I am trying to get JSON data to app, but getting JSON Exception
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private List<Project> projects = new ArrayList<>();
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
Button mFilterButton = (Button) findViewById(R.id.filter_button);
mFilterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.filter_menu);
popupMenu.show();
}
});
Button mSortButton = (Button) findViewById(R.id.sort_button);
mSortButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.sort_menu);
popupMenu.show();
}
});
new GSONExecution().execute();
}
private class GSONExecution extends AsyncTask<Void, Void, Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
String urlString = "http://starlord.hackerearth.com/kickstarter";
try {
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
int res = httpURLConnection.getResponseCode();
if (res == 200){
InputStream inputStream = httpURLConnection.getInputStream();
String s = convertStreamToString(inputStream);
Log.v("Response :" , " is "+ s);
JSONObject rootObject = new JSONObject(s);
JSONArray jsonArray = rootObject.getJSONArray("");
for (int i=0; i<=jsonArray.length(); i++){
JSONObject contactObject = jsonArray.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean isOperationCompleted) {
super.onPostExecute(isOperationCompleted);
if (isOperationCompleted){
if (progressDialog.isShowing()){
progressDialog.dismiss();
}
ProjectAdapter adapter = new ProjectAdapter(MainActivity.this, projects);
mListView.setAdapter(adapter);
}
}
#NonNull
private String convertStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);
String line;
while ((line = bufferedReader.readLine()) != null)
stringBuilder.append(line).append("\n");
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
}
Project
public class Project {
String mtitle;
Integer mPleadges;
Integer mBackers;
String mNoDays;
public String gettitle() {
return mtitle;
}
public void settitle(String mtitle) {
this.mtitle = mtitle;
}
public Integer getPleadges() {
return mPleadges;
}
public void setPleadges(Integer mPleadges) {
this.mPleadges = mPleadges;
}
public Integer getBackers() {
return mBackers;
}
public void setBackers(Integer mBackers) {
this.mBackers = mBackers;
}
public String getNoDays() {
return mNoDays;
}
public void setNoDays(String mNoDays) {
this.mNoDays = mNoDays;
}
}
ProjectAdapter
class ProjectAdapter extends BaseAdapter{
private List<Project> mList;
private Context mContext;
public ProjectAdapter(MainActivity mainActivity, List<Project> projects) {
this.mList = projects;
this.mContext = mainActivity;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.project_details,null,false);
final TextView projectName = (TextView) convertView.findViewById(R.id.projectName);
TextView pleadge = (TextView) convertView.findViewById(R.id.pledges);
TextView backers = (TextView) convertView.findViewById(R.id.backers);
projectName.setText(mList.get(position).gettitle());
pleadge.setText(mList.get(position).getPleadges());
backers.setText(mList.get(position).getBackers());
return convertView;
}
}
I am getting org.json.JSONException: Value
at org.json.JSON.typeMismatch(JSON.java:111)
I hope you understand problem, I am still in learning stage so please give brief answer so that i can understand.
You are getting JSONArray from Response and trying to hold on JSONObject which causes org.json.JSONException: Value at org.json.JSON.typeMismatch(JSON.java:111) error
Try this
try {
JSONArray jsonArrayLST = new JSONArray(s);
for (int i = 0; i < jsonArrayLST.length(); i++) {
JSONObject contactObject= jsonArrayLST.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, you need to change in your adapter while setting item to textview, because your are setting int value which causes you android.content.res.Resources$NotFoundException: String resource ID error
pleadge.setText(String.valueOf(mList.get(position).getPleadges()));
backers.setText(String.valueOf(mList.get(position).getBackers()));
I am newbie to android and working on a custom listView with custom adapter,I am having a listview and edittext,I want to add a searching feature using this,When user input some characters the listview should be filtered depending on the input,I have tried as below, Could someone help me to resolve this,
BusAdapter
public class BusAdapter extends BaseAdapter implements Filterable{
public ArrayList<Bus> BusArray;
private Context mContext;
// Original Values
private ArrayList<Bus> mDisplayedValues;
public BusAdapter(Context paramContext, ArrayList<Bus> BusArray) {
this.mContext = paramContext;
this.mDisplayedValues = BusArray;
this.BusArray = BusArray;
}
public int getCount() {
return this.BusArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_bus, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.tv_rtname = ((TextView) paramView.findViewById(R.id.tv_rtname));
localViewholder.tv_from = ((TextView) paramView.findViewById(R.id.tv_from));
localViewholder.tv_to = ((TextView) paramView.findViewById(R.id.tv_to));
localViewholder.tv_freq = ((TextView) paramView.findViewById(R.id.tv_fr));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.tv_from
.setText(BusArray.get(paramInt).getRoute_from());
localViewholder.tv_to
.setText(BusArray.get(paramInt).getRoute_to());
localViewholder.tv_rtname
.setText(BusArray.get(paramInt).getRoute_name());
return paramView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
mDisplayedValues = (ArrayList<Bus>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<Bus> FilteredArrList = new ArrayList<Bus>();
if (BusArray == null) {
BusArray = new ArrayList<Bus>(mDisplayedValues); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = BusArray.size();
results.values = BusArray;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < BusArray.size(); i++) {
String data = BusArray.get(i).getRoute_name();
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(new Bus(BusArray.get(i).route_id,BusArray.get(i).route_name,BusArray.get(i).route_details,BusArray.get(i).route_from,BusArray.get(i).route_to));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
//get filter
//end
static class Viewholder {
TextView tv_from;
TextView tv_to;
TextView tv_rtname;
TextView tv_freq;
}
}
Activity
public class BusTimingActivity extends AppCompatActivity {
ListView lv_bus;
ArrayList<Bus> busList;
ProgressDialog pDialog;
InputStream inputStream = null;
String result;
BusAdapter adapter;
EditText et_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_bus_timings);
lv_bus = (ListView)findViewById(R.id.lv_bus);
et_search = (EditText)findViewById(R.id.et_search);
busList = new ArrayList<>();
et_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
new GETBUSROUTES().execute();
}
//GET ALL BUS ROUTES..
public class GETBUSROUTES extends AsyncTask<Void, Void, Void> {
StringEntity se;
String url;
#Override
protected void onPreExecute() {
super.onPreExecute();
busList.clear();
pDialog = new ProgressDialog(BusTimingActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
busList.clear();
}
#Override
protected Void doInBackground(Void... params) {
url = Const.API_URL;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> valueparams = new ArrayList<NameValuePair>();
valueparams.add(new BasicNameValuePair("form_type", "all_bus_routes"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(valueparams));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String json = "";
//getting string entity to http..!!!
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
result = total.toString();
try {
JSONArray results = new JSONArray(result);
for (int i = 0; i<results.length() ; i++) {
JSONObject c = results.getJSONObject(i);
Bus bus = new Bus();
bus.setRoute_id(c.getString("route_id"));
bus.setRoute_details(c.getString("route_details"));
bus.setRoute_from(c.getString("route_from"));
bus.setRoute_to(c.getString("route_to"));
bus.setRoute_name(c.getString("route_name"));
busList.add(bus);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("====RESPONSE FOR BUSES====>" + result.toString());
} else
result = "Did not work!";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// execute HTTP post request
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
//
if(busList.size()>0){
adapter = new BusAdapter(BusTimingActivity.this,busList);
lv_bus.setAdapter(adapter);
adapter.notifyDataSetChanged();
}else{
Toast.makeText(BusTimingActivity.this,"No Routes Found",Toast.LENGTH_SHORT).show();
}
}
}
Bus.java
public class Bus {
public String route_id;
public String route_name;
public Bus(String route_id, String route_name, String route_details, String route_from, String route_to) {
this.route_id = route_id;
this.route_name = route_name;
this.route_details = route_details;
this.route_from = route_from;
this.route_to = route_to;
}
public Bus() {
}
public String route_details;
public String getRoute_from() {
return route_from;
}
public void setRoute_from(String route_from) {
this.route_from = route_from;
}
public String getRoute_id() {
return route_id;
}
public void setRoute_id(String route_id) {
this.route_id = route_id;
}
public String getRoute_name() {
return route_name;
}
public void setRoute_name(String route_name) {
this.route_name = route_name;
}
public String getRoute_details() {
return route_details;
}
public void setRoute_details(String route_details) {
this.route_details = route_details;
}
public String getRoute_to() {
return route_to;
}
public void setRoute_to(String route_to) {
this.route_to = route_to;
}
public String route_from;
public String route_to;
}
Since it seems you are just filtering on the getRoute_name() it may be easier to extend ArrayAdapter<Bus> which will do the filtering for you and then override the toString() for your Bus object to return the route name.
I don't think it's your filtering problem, but the getItem() should return a Bus object from your array list and not an Integer.
As #Daniel Wilson pointed out, your code is a bit difficut to read because of your variables that start with capial letters, it makes it look like a static method call.
I want to parse data and images via url of json.
I have used following code to do same. But i am not getting why the images disappear when i scroll down.
Can Anyone please tell me how can i stop to disappear images when i scroll down ?
Images are loading randomly how can i fix it?
Please find below link of source code :-
http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://milagro.in/wip/apps/n/THDC2.json");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).gettata_project_name(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.settata_project_name(object.getString("tata_project_name"));
actor.setproject_Typology(object.getString("project_Typology"));
actor.setproject_logo_url(object.getString("project_logo_url"));
actor.setprice(object.getString("price"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.Projectname = (TextView) v.findViewById(R.id.Projectname);
holder.typology = (TextView) v.findViewById(R.id.typology);
holder.price = (TextView) v.findViewById(R.id.price);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.imageview.setImageResource(R.drawable.ic_launcher);
//new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.Projectname.setText(actorList.get(position).gettata_project_name());
holder.typology.setText(actorList.get(position).getproject_Typology());
holder.price.setText("Price: " + actorList.get(position).getprice());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView Projectname;
public TextView typology;
public TextView price;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public class Actors {
private String tata_project_name;
private String project_Typology;
private String project_logo_url;
private String price;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String tata_project_name, String project_Typology,String project_logo_url, String price ) {
super();
this.tata_project_name = tata_project_name;
this.project_Typology = project_Typology;
this.project_logo_url = project_logo_url;
this.price = price;
}
public String gettata_project_name() {
return tata_project_name;
}
public void settata_project_name(String tata_project_name) {
this.tata_project_name = tata_project_name;
}
public String getproject_Typology() {
return project_Typology;
}
public void setproject_Typology(String project_Typology) {
this.project_Typology = project_Typology;
}
public String getproject_logo_url() {
return project_logo_url;
}
public void setproject_logo_url(String project_logo_url) {
this.project_logo_url = project_logo_url;
}
public String getprice() {
return price;
}
public void setprice(String price) {
this.price = price;
}
}
try this library Picaso this is the best image loading library from url.
After using Volley library The problem is solved.
I have one spinner and I want to to populate the custom listview with the the data according to spinner selection. Data is coming from mysql database. Currently I am able to get the data from different spinner selection but the problem is when I try to add the data in listview it doesn't remove previous data from listview.
I tried listAdapter.notifyDataSetChanged() but this didn,t worked for me. Even I created 2 adapters for different spinner selections and tried to add them to list according to spinner selection but this gives me blank list.
I saw multiple solutions for my problem but nothing worked for me.
So please give me some suitable idea for adding different data to listview according to spinner selection.
Thanks in advance
this is my adapter class
public class ListAdapter extends ArrayAdapter {
//static String get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static List list=new ArrayList();
static String[] get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static ArrayList<String> empcode = new ArrayList<String>();
static ArrayList<String> from = new ArrayList<String>();
static ArrayList<String> to = new ArrayList<String>();
static ArrayList<String> lv_type = new ArrayList<String>();
static ArrayList<String> nod = new ArrayList<String>();
static int count=0;
int i;
static int arr_length;
public ListAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Details object) {
super.add(object);
list.add(object);
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
super.unregisterDataSetObserver(observer);
}
public int getCount() {
return list.size();
}
#Override
public Details getItem(int position) {
return (Details) list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
final DetailsHolder detailsHolder;
if(row==null)
{
LayoutInflater layoutInflater=(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.list_layout_approval, parent, false);
detailsHolder=new DetailsHolder();
detailsHolder.empcode=(TextView) row.findViewById(R.id.empcode1);
detailsHolder.empname=(TextView) row.findViewById(R.id.empname1);
detailsHolder.appdate=(TextView) row.findViewById(R.id.appdate1);
detailsHolder.lv_type=(TextView) row.findViewById(R.id.lv_type1);
detailsHolder.from=(TextView) row.findViewById(R.id.from1);
detailsHolder.to=(TextView) row.findViewById(R.id.to1);
detailsHolder.nod=(TextView) row.findViewById(R.id.nod1);
detailsHolder.reason=(TextView) row.findViewById(R.id.reason1);
detailsHolder.status=(TextView) row.findViewById(R.id.status1);
DetailsHolder.cb2=(CheckBox) row.findViewById(R.id.cb2);
DetailsHolder.cb2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
count=count+1;
empcode.add((String) detailsHolder.empcode.getText());
from.add((String) detailsHolder.from.getText());
to.add((String) detailsHolder.to.getText());
lv_type.add((String) detailsHolder.lv_type.getText());
nod.add((String) detailsHolder.nod.getText());
}
else{
count=count-1;
empcode.remove(position);
from.remove(position);
to.remove(position);
lv_type.remove(position);
nod.remove(position);
}
arr_length=empcode.size()+from.size()+to.size()+lv_type.size()+nod.size();
}
});
row.setTag(detailsHolder);
}
else{
detailsHolder=(DetailsHolder) row.getTag();
}
Details details=(Details)this.getItem(position);
detailsHolder.empcode.setText(details.getEmpcode());
detailsHolder.empname.setText(details.getEmpname());
detailsHolder.appdate.setText(details.getApplyDate());
detailsHolder.lv_type.setText(details.getLeave_type());
detailsHolder.from.setText(details.getFrom());
detailsHolder.to.setText(details.getTo());
detailsHolder.nod.setText(details.getNod());
detailsHolder.reason.setText(details.getReason());
detailsHolder.status.setText(details.getStatus());
return row;
}
static class DetailsHolder
{
TextView empcode,empname,appdate,lv_type,from,to,nod,reason,status;
EditText remark;
static CheckBox cb2;
}
}
below is details class:-
public class Details {
private String empcode,empname,applyDate,leave_type,from,to,nod,reason,remark,status;
public Details(String empcode,String empname,String applyDate,String leave_type,String from,
String to,String nod,String reason,String status){
this.setEmpcode(empcode);
this.setEmpname(empname);
this.setApplyDate(applyDate);
this.setLeave_type(leave_type);
this.setFrom(from);
this.setTo(to);
this.setNod(nod);
this.setReason(reason);
this.setStatus(status);
}
public String getEmpcode() {
return empcode;
}
public void setEmpcode(String empcode) {
this.empcode = empcode;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getApplyDate() {
return applyDate;
}
public void setApplyDate(String applyDate) {
this.applyDate = applyDate;
}
public String getLeave_type() {
return leave_type;
}
public void setLeave_type(String leave_type) {
this.leave_type = leave_type;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getNod() {
return nod;
}
public void setNod(String nod) {
this.nod = nod;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
And in mainActivity I am passing data as follows:
public class Leave_approval extends Activity {
String JSON_STRING,php_result,LeaveType,empcode,FullName,ApplyDate,From,To,NOD,Reason,Status,bundle_id,approve_bkg_result;
String from_date,to_date,appdate;
String LeaveType1,empcode1,FullName1,ApplyDate1,From1,To1,NOD1,Reason1,Status1,bundle_id1,from_date1,to_date1,appdate1;
String[] status_data;
String[] empcode_val,lv_type_val,nod_value,status_val,from_value,to_value;
JSONObject jsonObject;
JSONArray jsonArray;
String[] date_list;
Details details;
TextView head;
ListAdapter listAdapter;
Approve_List_adapter approve_adapter;
ListView listView;
CheckBox cb1;
static Boolean cb_status;
int i;
Spinner status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.leave_approval);
listView=(ListView) findViewById(R.id.list);
cb1=(CheckBox) findViewById(R.id.cb1);
status=(Spinner) findViewById(R.id.status);
listAdapter=new ListAdapter(this, R.layout.list_layout_approval);
// approve_adapter=new Approve_List_adapter(this, R.layout.approve_list_adapter);
listView.setAdapter(listAdapter);
//listView.setAdapter(approve_adapter);
head=(TextView) findViewById(R.id.head);
Bundle b = getIntent().getExtras();
php_result=b.getString("json_data");
bundle_id = b.getString("string");
status_data=getResources().getStringArray(R.array.status);
ArrayAdapter<String> adapter=new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,status_data);
status.setAdapter(adapter);
status.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
String status_changed=arg0.getItemAtPosition(arg2).toString();
if(status_changed.equals("Approved"))
{
LeaveApprovedStatus bkg=new LeaveApprovedStatus(getApplicationContext());
bkg.execute(bundle_id);
}
else{
//Toast.makeText(getApplicationContext(), status_changed, Toast.LENGTH_SHORT).show();
try {
jsonObject=new JSONObject(php_result);
jsonArray=jsonObject.getJSONArray("server_response");
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i);
LeaveType=c.getString("LeaveType");
empcode=c.getString("empcode");
FullName=c.getString("FullName");
ApplyDate=c.getString("ApplyDate");
From=c.getString("From");
To=c.getString("To");
NOD=c.getString("NOD");
Reason=c.getString("Reason");
Status=c.getString("Status");
String[] from_array=From.split("-");
String[] to_array=To.split("-");
String[] apply_array=ApplyDate.split("-");
String from_date,to_date,appdate;
if(from_array[1].equals("01"))
from_array[1]="jan";
if(from_array[1].equals("02"))
from_array[1]="Feb";
if(from_array[1].equals("03"))
from_array[1]="Mar";
if(from_array[1].equals("04"))
from_array[1]="Apr";
if(from_array[1].equals("05"))
from_array[1]="May";
if(from_array[1].equals("06"))
from_array[1]="Jun";
if(from_array[1].equals("07"))
from_array[1]="Jul";
if(from_array[1].equals("08"))
from_array[1]="Aug";
if(from_array[1].equals("09"))
from_array[1]="Sep";
if(from_array[1].equals("10"))
from_array[1]="Oct";
if(from_array[1].equals("11"))
from_array[1]="Nov";
if(from_array[1].equals("12"))
from_array[1]="Dec";
if(to_array[1].equals("01"))
to_array[1]="jan";
if(to_array[1].equals("02"))
from_array[1]="Feb";
if(to_array[1].equals("03"))
to_array[1]="Mar";
if(to_array[1].equals("04"))
to_array[1]="Apr";
if(to_array[1].equals("05"))
to_array[1]="May";
if(to_array[1].equals("06"))
to_array[1]="Jun";
if(to_array[1].equals("07"))
to_array[1]="Jul";
if(to_array[1].equals("08"))
to_array[1]="Aug";
if(to_array[1].equals("09"))
to_array[1]="Sep";
if(to_array[1].equals("10"))
to_array[1]="Oct";
if(to_array[1].equals("11"))
to_array[1]="Nov";
if(to_array[1].equals("12"))
to_array[1]="Dec";
if(apply_array[1].equals("01"))
apply_array[1]="jan";
if(apply_array[1].equals("02"))
apply_array[1]="Feb";
if(apply_array[1].equals("03"))
apply_array[1]="Mar";
if(apply_array[1].equals("04"))
apply_array[1]="Apr";
if(apply_array[1].equals("05"))
apply_array[1]="May";
if(apply_array[1].equals("06"))
apply_array[1]="Jun";
if(apply_array[1].equals("07"))
apply_array[1]="Jul";
if(apply_array[1].equals("08"))
apply_array[1]="Aug";
if(apply_array[1].equals("09"))
apply_array[1]="Sep";
if(apply_array[1].equals("10"))
apply_array[1]="Oct";
if(apply_array[1].equals("11"))
apply_array[1]="Nov";
if(apply_array[1].equals("12"))
apply_array[1]="Dec";
from_date=from_array[2]+"-"+from_array[1]+"-"+from_array[0];
to_date=to_array[2]+"-"+to_array[1]+"-"+to_array[0];
appdate=apply_array[2]+"-"+apply_array[1]+"-"+apply_array[0];
details=new Details(empcode,FullName,appdate,LeaveType,from_date,to_date,NOD,Reason,Status);
listAdapter.add(details);
//listView.invalidate();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
public void approve(View view){
//Toast.makeText(getApplicationContext(), String.valueOf(ListAdapter.count), Toast.LENGTH_SHORT).show();
ArrayList<String> emplist=new ArrayList<>();
ArrayList<String> fromlist=new ArrayList<>();
ArrayList<String> tolist=new ArrayList<>();
ArrayList<String> lv_typelist=new ArrayList<>();
ArrayList<String> nodlist=new ArrayList<>();
ArrayList<String> status=new ArrayList<>();
emplist=ListAdapter.getemplist();
fromlist=ListAdapter.getfromlist();
tolist=ListAdapter.gettolist();
lv_typelist=ListAdapter.getlv_typelist();
nodlist=ListAdapter.getnodlist();
status.add("Approved");
JSONArray jArr1= new JSONArray();
for(String data:emplist)
{
jArr1.put(data);
}
JSONArray jArr2= new JSONArray();
for(String data:fromlist)
{
jArr2.put(data);
}
JSONArray jArr3= new JSONArray();
for(String data:tolist)
{
jArr3.put(data);
}
JSONArray jArr4= new JSONArray();
for(String data:lv_typelist)
{
jArr4.put(data);
}
JSONArray jArr5= new JSONArray();
for(String data:status)
{
jArr5.put(data);
}
JSONArray jArraySet = new JSONArray();
jArraySet.put(jArr1);
jArraySet.put(jArr2);
jArraySet.put(jArr3);
jArraySet.put(jArr4);
jArraySet.put(jArr5);
String json_string=String.valueOf(jArraySet);
// Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(json_string);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
listView.onWindowFocusChanged(true);
listView.invalidate();
listView.invalidateViews();
}
}
public void reject(View view){
ArrayList<String> emplist=new ArrayList<>();
ArrayList<String> fromlist=new ArrayList<>();
ArrayList<String> tolist=new ArrayList<>();
ArrayList<String> lv_typelist=new ArrayList<>();
ArrayList<String> nodlist=new ArrayList<>();
ArrayList<String> status=new ArrayList<>();
emplist=ListAdapter.getemplist();
fromlist=ListAdapter.getfromlist();
tolist=ListAdapter.gettolist();
lv_typelist=ListAdapter.getlv_typelist();
nodlist=ListAdapter.getnodlist();
status.add("Rejected");
JSONArray jArr1= new JSONArray();
for(String data:emplist)
{
jArr1.put(data);
}
JSONArray jArr2= new JSONArray();
for(String data:fromlist)
{
jArr2.put(data);
}
JSONArray jArr3= new JSONArray();
for(String data:tolist)
{
jArr3.put(data);
}
JSONArray jArr4= new JSONArray();
for(String data:lv_typelist)
{
jArr4.put(data);
}
JSONArray jArr5= new JSONArray();
for(String data:status)
{
jArr5.put(data);
}
JSONArray jArraySet = new JSONArray();
jArraySet.put(jArr1);
jArraySet.put(jArr2);
jArraySet.put(jArr3);
jArraySet.put(jArr4);
jArraySet.put(jArr5);
String json_string=String.valueOf(jArraySet);
//Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(json_string);
}
public class BackgroundTask extends AsyncTask<String,Void,String> {
AsyncResponse delegate = null;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
}
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/neha/leave_approval_json.php";
String json_data = params[0];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("json_data","UTF-8")+"="+URLEncoder.encode(json_data,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// }
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_SHORT).show();
}
}
class LeaveApprovedStatus extends AsyncTask<String, Void, String>
{
String json_url;
Context ctx;
LeaveApprovedStatus(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
json_url = "http://10.0.2.2/neha/leave_approval_approvedStatus.php";
final String empcode = params[0];
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("empcode","UTF-8")+"="+URLEncoder.encode(empcode,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
StringBuilder stringBuilder1=new StringBuilder();
while((JSON_STRING=bufferedReader.readLine())!=null)
{
stringBuilder1.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder1.toString().trim();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
approve_bkg_result=result;
Details details1=new Details (empcode1,FullName1,appdate1,LeaveType1,from_date1,to_date1,NOD1,Reason1,Status1);
listAdapter.add(details1);
listAdapter.notifyDataSetChanged();
listView.invalidate();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
So supposing you store your data in an ArrayList:
private ArrayList<VideoPreview> dataList = new ArrayList<>();
You can populate it in the spinner onItemSelectedListener:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position != currentPosition) {
dataList.clear();
dataList = myData[position];
dataListView.getAdapter().notifyOnDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Without knowing anything else of your problem and code, I cannot give you a more specific solution.
Your declaration of the adapter should look similar to this:
final DataAdapter adapter = new DataAdapter(getContext(), dataList);
dataListView.setAdapter(adapter);
If the data object you are passing is ArrayList<MyObject>
just make your custom adapter extend ArrayAdapter<MyObject> instead of BaseAdapter. Implement the required methods (leave default) and you should be fine.
I want to filter my listview according to what's inputted in my edittext but the listview is not being filtered. Hope there's anyone who can help me. Thank you in advance.
Here's my code for my adapter:
public class ListofCityAdapter extends ArrayAdapter implements Filterable{
int groupid;
ArrayList<City> records;
ArrayList<City> items;
Context context;
public ListofCityAdapter(Context context, int vg, int id, ArrayList<City> objects) {
super(context, vg, id, objects);
this.context = context;
groupid = vg;
this.records = objects;
} public int getCount() {
return records.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(groupid, parent, false);
TextView textName = (TextView) itemView.findViewById(R.id.city_name);
textName.setText(records.get(position).getCityName());
TextView cityregion = (TextView)itemView.findViewById(R.id.city_region);
cityregion.setText(records.get(position).getRegion());
ImageView image = (ImageView)itemView.findViewById(R.id.image);
new DownloadImageTask(image).execute(records.get(position).getImage());
return itemView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<City> results = new ArrayList<City>();
if (records == null)
records = items;
if (constraint != null) {
if (records != null && records.size() > 0) {
for (final City g : records) {
if (g.getCityName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
items = (ArrayList<City>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
Here's my ListofCity.class. this is
public class ListofCity extends Fragment implements AdapterView.OnItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
Spinner filter;
ListofCityAdapter cityAdapter;
GridView listCity;
ArrayList<City> records;
int id;
EditText search;
// SharedPreferences.Editor citylist;
String line=null;
String filtering,cityname;
SwipeRefreshLayout swipeLayout;
public ListofCity(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_listof_city, container, false);
context = getActivity();
records = new ArrayList<City>();
listCity = (GridView) view.findViewById(R.id.cities);
cityAdapter = new ListofCityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
search = (EditText) view.findViewById(R.id.inputSearch);
filter = (Spinner) view.findViewById(R.id.filter);
String categories[] = getResources().getStringArray(R.array.filtering);
ArrayAdapter<String> cat = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories);
cat.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
filter.setAdapter(cat);
listCity.setTextFilterEnabled(true);
filter.setOnItemSelectedListener(this);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(), City_attractions.class);
Toast.makeText(getActivity(), "Opening", Toast.LENGTH_LONG).show();
cityname = records.get(position).getCityName();
String info = records.get(position).getDescription();
String area = records.get(position).getArea();
String population = records.get(position).getPopulation();
String region = records.get(position).getRegion();
String province = records.get(position).getProvince();
myIntent.putExtra("cityname", cityname);
myIntent.putExtra("cityinfo", info);
myIntent.putExtra("cityarea", area);
myIntent.putExtra("citypopulation", population);
myIntent.putExtra("cityregion", region);
myIntent.putExtra("cityprovince", province);
startActivity(myIntent);
}
});
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
cityAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
return view;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
fetchCity fetch = new fetchCity();
switch (position){
case 0:
filtering ="All";
fetch.execute();
break;
case 1:
filtering ="Alphabetically";
fetch.execute();
break;
case 2:
filtering ="Region";
fetch.execute();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("filter", filtering));
try
{
records.clear();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getcity.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getActivity(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("cityName"));
p.setArea(json_data.getString("area"));
p.setPopulation(json_data.getString("population"));
p.setImage(json_data.getString("path"));
p.setDescription(json_data.getString("city_info"));
p.setProvince(json_data.getString("province"));
p.setRegion(json_data.getString("region"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}