I have listview All the values are delete and update properly but only the last value is not delete in the listview.
Added a full fragment code. Take a look
For example
If I have three values in the listview If I delete 1 and 2 its removing and listview refresh properly but the last one is not refreshed in the listview
private SwipeMenuListView mylistview;
String userid;
private EditText txtsearch;
private ArrayList<JobItem> jobitems;
private JobListAdapter adapter;
SwipeMenuCreator creator;
ImageLoader imageLoader;
DisplayImageOptions options;
public Fragment_Employer_MyJobList() {
}
public static float dp2px(Context context, int dipValue) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layoutjoblist, container, false);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(1000))
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.img_app_icon)
.showImageOnFail(R.drawable.img_app_icon)
.showImageOnLoading(R.drawable.img_app_icon).build();
mylistview = (SwipeMenuListView) rootView.findViewById(R.id.mylistview);
creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
openItem.setWidth((int) dp2px(getActivity(), 90));
// set item title
openItem.setTitle("DELETE");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
}
};
txtsearch = (EditText) rootView.findViewById(R.id.txtsearch);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
String text = txtsearch.getText().toString().toLowerCase(Locale.getDefault());
if (adapter != null)
adapter.filter(text);
}
});
return rootView;
}
SharedPreferences settings;
#Override
public void onResume() {
super.onResume();
jobitems = new ArrayList<JobItem>();
jobitems.clear();
adapter.notifyDataSetChanged();
settings = getActivity().getSharedPreferences(AppUtils.PREFS_NAME, Context.MODE_PRIVATE);
userid = settings.getString("userid", "");
AuthController.getStaticInstance().
employer_joblist(getActivity(), userid, APIConstants
.POST, new AuthControllerInterface.AuthControllerCallBack()
{
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONArray mainarray = new JSONArray(message);
for (int i = 0; i < mainarray.length(); i++) {
JSONObject json_job = mainarray.getJSONObject(i);
JobItem item = new JobItem();
item.Id = json_job.getString("ID");
item.EMPID = json_job.getString("EMPID");
item.TITLE = json_job.getString("TITLE");
item.DESC = json_job.getString("DESC");
item.CID = json_job.getString("CID");
item.PRICE = json_job.getString("PRICE");
item.LOCAT = json_job.getString("LOCAT");
item.ADATE = json_job.getString("ADATE");
item.FOLLOW = json_job.getString("FOLLOW");
JSONArray array = json_job.getJSONArray("IMAGES");
if (array.length() > 0) {
if (!array.isNull(0))
item.IMG1 = array.getString(0);
if (!array.isNull(1))
item.IMG2 = array.getString(1);
if (!array.isNull(2))
item.IMG3 = array.getString(2);
if (!array.isNull(3))
item.IMG4 = array.getString(3);
if (!array.isNull(4))
item.IMG5 = array.getString(4);
}
jobitems.add(item);
}
adapter = new JobListAdapter(getActivity(), jobitems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JobItem item = jobitems.get(position);
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
});
mylistview.setMenuCreator(creator);
mylistview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
// unfollow
userid = settings.getString("userid", "");
AuthController.getStaticInstance().employer_delete_job(getActivity(), userid, jobitems.get(position).Id, APIConstants.POST, new AuthControllerInterface.AuthControllerCallBack() {
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
// onResume();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
// onResume();
}
//setup
onResume();
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
} catch (JSONException e) {
e.printStackTrace();
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
e1.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
}
#Override
public void showLoading() {
AppUtils.showProgress(getActivity(), "Please wait...");
// onResume();
}
#Override
public void stopLoading() {
AppUtils.dismissProgress();
// onResume();
}
public class OnItemClickListner implements View.OnClickListener {
int mposition;
JobItem item;
public OnItemClickListner(int position, JobItem item) {
this.mposition = position;
this.item = item;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class JobListAdapter extends BaseAdapter {
LayoutInflater _inflater;
private List<JobItem> worldpopulationlist = null;
private ArrayList<JobItem> arraylist;
public JobListAdapter(Context context, List<JobItem> worldpopulationlist) {
_inflater = LayoutInflater.from(context);
this.worldpopulationlist = worldpopulationlist;
this.arraylist = new ArrayList<JobItem>();
this.arraylist.addAll(worldpopulationlist);
}
public int getCount() {
// TODO Auto-generated method stub
return worldpopulationlist.size();
}
public JobItem getItem(int position) {
// TODO Auto-generated method stub
return worldpopulationlist.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder _holder;
if (convertView == null) {
convertView = _inflater.inflate(R.layout.layout_job_row, null);
_holder = new ViewHolder();
_holder.txtjobtitle = (TextView) convertView
.findViewById(R.id.txtjobtitle);
_holder.txtjobbudget = (TextView) convertView
.findViewById(R.id.txtjobbudget);
_holder.txtjobdesc = (TextView) convertView
.findViewById(R.id.txtjobdesc);
_holder.imageviewjob = (ImageView) convertView
.findViewById(R.id.imageviewjob);
_holder.txtlocation = (TextView) convertView
.findViewById(R.id.txtlocation);
convertView.setTag(_holder);
} else {
_holder = (ViewHolder) convertView.getTag();
}
_holder.txtjobtitle.setText(worldpopulationlist.get(position).TITLE.trim());
_holder.txtjobbudget.setText(worldpopulationlist.get(position).PRICE.trim());
_holder.txtjobdesc.setVisibility(View.VISIBLE);
_holder.txtjobbudget.setVisibility(View.GONE);
_holder.txtjobdesc.setText(worldpopulationlist.get(position).DESC);
imageLoader.displayImage(worldpopulationlist.get(position).IMG1, _holder.imageviewjob, options);
_holder.txtlocation.setText(worldpopulationlist.get(position).LOCAT.trim());
//convertView.setOnClickListener(new OnItemClickListner(position, worldpopulationlist.get(position)));
return convertView;
}
private class ViewHolder {
ImageView imageviewjob;
TextView txtjobtitle, txtjobdesc;
TextView txtlocation, txtjobbudget;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (JobItem wp : arraylist) {
if (wp.TITLE.toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
you have to tell your ListView that something changed in it's former List by calling notifyDataSetChanged() method of your adapter
Also you should not create a new instance of ArrayList, but only clear the old instance. Don't forget to check for null before clearing.
try calling the adapter again with a null like.
setListAdapter()
Related
I have worked with the concept of filter that have to filter the job from job list based on skills and some list or there.
https://postimg.org/image/g3p1z6lbd/ - DashBoard Fragment.
About DashBoardFragment:
Contains job list view.
Dash Filter Button. - which redirect to the Filter screen.
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("onItemClick", "onItemClick <---- ");
Intent toPositionDetail = new Intent(getActivity(), PositionDetailScreenRefactor.class);
toPositionDetail.putExtra("id", dashRowList1.get(position).getDashId());
startActivity(toPositionDetail);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
}
});
final int totalJobCount = SessionStores.gettotalJobList(getActivity());
Log.e("totalJobCount", "totalJobCount----" + totalJobCount);
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Please Wait. It is Loading..job orders....");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
// progress.dismiss();
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}}
DashBoardTask:
public class DashBoardTask {
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
//Getting Response and Assign into model Class
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
DashListAdapter:
________________
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
Log.e("get pos", "get pooooossss---->" + dashRowList.get(position));
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
//Assign the value into screen
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
}
the above code for displaying dashboard fragment list.
https://postimg.org/image/nqvp1dud9/ - This link is FilterScreen
By using this image if i filter the job based on the designed UI detail. That should replace into the DashboadFragment list The result should display into the DashBoard Fragment. How can I add pagination on Filter screen the same which have in DashBoardFragment.
I am using custom list view inside fragment(From Api). on orientation change data is still in array list and also list view get notified but it hides when screen rotates.
here is the code:
public class FragNotice extends Fragment implements View.OnClickListener {
ListAdapter listAdapter;
ListView listView;
EditText editTextNotice;
private Button btnSearch;
private Button btnClear;
private int incre = 1;
private boolean boolScroll = true;
public FragNotice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
setRetainInstance(true);
search(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return init(inflater.inflate(R.layout.notice_activity, container, false));
}
private View init(View view) {
editTextNotice = (EditText) view.findViewById(R.id.editTextNotice);
btnSearch = (Button) view.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
btnClear = (Button) view.findViewById(R.id.btnClear);
btnClear.setOnClickListener(this);
listView = (ListView) view.findViewById(R.id.listViewNotice);
listView.setOnScrollListener(onScrollListener());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), new ArrayList<ListRowItem>());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
AsyncRequest.OnAsyncRequestComplete onAsyncRequestComplete = new AsyncRequest
.OnAsyncRequestComplete() {
#Override
public void asyncResponse(String response, int apiKey) {
switch (apiKey) {
case 1:
listView(response);
break;
}
}
};
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnClear) {
incre = 1;
boolScroll = true;
editTextNotice.setText(null);
if (listAdapter != null)
listAdapter.clear();
search(true);
} else if (v.getId() == R.id.btnSearch) {
String std = editTextNotice.getText().toString();
if (std.trim().length() > 1) {
incre = 1;
boolScroll = true;
if (listAdapter != null)
listAdapter.clear();
try {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(new View(getActivity()).getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
// TODO: handle exception
}
search(false);
} else
Toast.makeText(getActivity(),
"Please enter atleast two character.", Toast.LENGTH_LONG)
.show();
}
}
class ListAdapter extends ArrayAdapter<ListRowItem> {
private final Context context;
public ListAdapter(Context asyncTask, java.util.List<ListRowItem> items) {
super(asyncTask, R.layout.notice_listitem, items);
this.context = asyncTask;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final ListRowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notice_listitem, parent, false);
holder = new ViewHolder();
holder.txtSno = (TextView) convertView.findViewById(R.id.txtSno);
holder.txtNoticePublishDate = (TextView) convertView.findViewById(R.id
.txtNoticePublishDate);
holder.btnView = (Button) convertView.findViewById(R.id.btnView);
holder.txtNoticeDescription = (TextView) convertView.findViewById(R.id
.txtNoticeDescription);
holder.txtNoticeName = (TextView) convertView.findViewById(R.id.txtNoticeName);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtSno.setText(String.valueOf(position + 1));
holder.txtNoticeDescription.setText(new AppUtility().TitleCase(rowItem.getDescription
()));
holder.txtNoticeName.setText(new AppUtility().TitleCase(rowItem.getFileTitle()));
try {
holder.txtNoticePublishDate.setText(String.valueOf((new SimpleDateFormat("dd MMM " +
"yyyy HH:mm:ss", Locale.US)).format((new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ss", Locale.US)).parse(rowItem.getUpdateDate()))));
} catch (ParseException e) {
holder.txtNoticePublishDate.setText(new AppUtility().TitleCase(rowItem
.getUpdateDate()));
}
holder.btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return convertView;
}
/*private view holder class*/
private class ViewHolder {
TextView txtSno;
TextView txtNoticeName;
TextView txtNoticeDescription;
TextView txtNoticePublishDate;
Button btnView;
}
}
class ListRowItem {
private final String FileTitle;
private final String Description;
private final String ContentType;
private final int DocumentUploadID;
private final String UpdateDate;
ListRowItem() {
this.FileTitle = "";
this.Description = "";
this.ContentType = "";
this.DocumentUploadID = 0;
this.UpdateDate = "";
}
ListRowItem(String fileTitle, String description, String contentType, int
documentUploadID, String updateDate) {
this.FileTitle = fileTitle;
this.Description = description;
this.ContentType = contentType;
this.DocumentUploadID = documentUploadID;
this.UpdateDate = updateDate;
}
public String getFileTitle() {
return FileTitle;
}
public int getDocumentUploadID() {
return DocumentUploadID;
}
public String getUpdateDate() {
return UpdateDate;
}
public String getDescription() {
return Description;
}
public String getContentType() {
return ContentType;
}
}
private void listView(String response) {
try {
ArrayList<ListRowItem> lstItem;
if(listAdapter==null){
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
listAdapter = new ListAdapter(getActivity(), lstItem);
} else {
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
listAdapter.addAll(lstItem);
} else {
for (ListRowItem items : lstItem) {
listAdapter.add(items);
}
}
}
if (listAdapter != null)
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
private AbsListView.OnScrollListener onScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 5;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= count - threshold) {
if (boolScroll) {
if (editTextNotice.getText().toString().trim().length() > 0)
search(false);
else
search(true);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
private void search(boolean bool) {
String URL;
if (bool) {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/0/" + incre;
incre = incre + 1;
} else {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/" +
editTextNotice.getText().toString().trim() + "/" + incre;
incre = incre + 1;
}
AsyncRequest asyncRequest;
if (incre > 2)
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
null, 1);
else
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
"Fetching data", 1);
asyncRequest.execute(URL);
}
}
You need to load the data into the ListView again. You are binding the ListView to an adapter, you need to do it in onConfigurationChanged() method.
When orientation changes the activity reloads again.So you have to override onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Your Code Here
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Your Code Here
}
}
create a directory layout-land in the resources copy the your .xml file there align and set the Edittext and Button according to landscape layout .may be it solved your problem if the listview doest not get enough space to show in landscape layout
In onViewCreated(View view, Bundle savedInstanceState) method above you are setting new empty arraylist every time. So the previous items which are loaded are removed from adapter even though it is retained by setRetainInstance(true)
So you should have a Field that holds the arraylist and pass that field to adapter
private ArrayList<ListRowItem> listItems = new ArrayList<>()
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), listItems);//pass the Arraylist here
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
Then in private void listView(String response) method, add items to that listview created above as
listItems = new Gson().fromJson(response, listType);
listAdapter.notifyDataSetChanged();
I've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#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 (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.
I have and android app that works on android 4.0 great, but it crashes on android 4.3 and 4.4. I get this from the logCat
01-11 14:40:27.669: E/ACRA(25835): ACRA caught a IllegalStateException exception for quran. Building report.
01-11 14:40:27.789: E/AndroidRuntime(25835): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131099688, class android.widget.ListView) with Adapter(class quran.functions.PlaylistAdapter)]
Here is my code:
public class Playlist extends FragmentActivity {
private ListView list;
private Button manager, downloadAll;
private TextView reciter;
public static PlaylistAdapter adapter;
private ArrayList<Songs> songs;
private int RECITER_ID;
private String url, title, label;
private SlidingMenu slidingMenu;
private DatabaseHelper db;
private ImageView nowPlaying, back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
initWidgets();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(Playlist.this, PlayerFinal.class);
intent.putExtra("songs", songs);
if (getIntent().getIntExtra("duaa", -1) == 115)
intent.putExtra("lang", 115);
intent.putExtra("position", position);
intent.putExtra("fromClass", this.getClass() + "");
// intent.putExtra("mp3link", mp3link);
startActivity(intent);
}
});
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
XmlMapParser m = new XmlMapParser(Playlist.this, RECITER_ID);
HashMap<String, ArrayList<String>> map = m.convert();
map.keySet();
label = map.get("RecitorLabel").get(0);
title = map.get("Title").get(0);
url = map.get("Link").get(0);
back = (ImageView) findViewById(R.id.playlist_back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
db.openDB();
for (int i = 1; i < map.get("Link").size(); i++) {
if (db.isDownloaded(i, title, RECITER_ID)) {
songs.add(new Songs(i, map.get("Title").get(i),
Environment.getExternalStorageDirectory()
.getPath()
+ "/"
+ getString(R.string.app_name)
+ "/"
+ title
+ "/"
+ map.get("Title").get(i)
+ ".mp3", title, true, RECITER_ID,
false));
} else
songs.add(new Songs(i, map.get("Title").get(i), url
+ label + "/"
+ new DecimalFormat("000").format(i) + ".mp3",
title, false, RECITER_ID, false));
}
db.closeDB();
// Log.v("--",m.convert().get("Link").get(1));
// [RecitorLabel, Title, Link] THIS ARE THE KEYS m
// Log.v("--", map.get("RecitorLabel").get(0));
// Log.v("--", map.get("Link").get(1));
return null;
}
protected void onPostExecute(Void result) {
adapter = new PlaylistAdapter(Playlist.this, songs);
list.setAdapter(adapter);
reciter.setText(songs.get(0).getRecitorName());
};
}.execute();
}
#Override
public void onBackPressed() {
if (slidingMenu.isMenuShowing()) {
slidingMenu.toggle();
} else {
super.onBackPressed();
}
}
#Override
protected void onResume() {
super.onResume();
try {
if (Tplayer.getInstance().isPlaying()) {
adapter = new PlaylistAdapter(this, songs);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
this.slidingMenu.toggle();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.slidingMenu.toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initWidgets() {
db = new DatabaseHelper(this);
manager = (Button) findViewById(R.id.playlist_download_manager);
manager.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Playlist.this, DownloadManager.class);
startActivity(intent);
}
});
reciter = (TextView) findViewById(R.id.playlist_reciter_name_top);
list = (ListView) findViewById(R.id.playlist_list);
downloadAll = (Button) findViewById(R.id.playlist_download_all);
manager = (Button) findViewById(R.id.playlist_download_manager);
songs = new ArrayList<Songs>();
RECITER_ID = getIntent().getIntExtra("filename", -1);
// downloadAll.setOnClickListener(new OnClickListener() {
//
// #Override
// public void onClick(View v) {
// new DownloadAll(Playlist.this, songs);
// db.openDB();
// for (int i = 0; i < songs.size(); i++) {
// db.addDownloaded(songs.get(i).getNumber(), songs.get(i)
// .getLink(), 0, songs.get(i).getRecitorID(), "",
// songs.get(i).getTitle());
// }
// db.closeDB();
// }
// });
nowPlaying = (ImageView) findViewById(R.id.playlist_now_playing);
nowPlaying.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Tplayer tplayer = Tplayer.getInstance();
if (tplayer.isPlaying()) {
Intent intent = new Intent(Playlist.this, PlayerFinal.class);
if (tplayer.isPlaying())
intent.putExtra("songs", tplayer.getSongs());
else
intent.putExtra("songs", songs);
if (tplayer.getSongs().size() == 14)
intent.putExtra("lang", 115);
intent.putExtra("position", tplayer.getPosition());
startActivity(intent);
}
}
});
// Jeremy Feinstein slidinglistadapter line 94
slidingMenu = new SlidingMenu(this);
slidingMenu.setMode(SlidingMenu.LEFT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setShadowWidthRes(R.dimen.slidingmenu_shadow_width);
slidingMenu.setShadowDrawable(R.drawable.slidingmenu_shadow);
slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
slidingMenu.setFadeDegree(0.35f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
slidingMenu.setMenu(R.layout.slidingmenu);
}
}
and my playlist adapter class:
public class PlaylistAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
private ArrayList<Songs> data;
private DatabaseHelper db;
private SharedPreferences prefs;
int playpos;
int recitorID;
public PlaylistAdapter(Activity a, ArrayList<Songs> songs) {
activity = a;
data = songs;
db = new DatabaseHelper(a);
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
prefs = activity.getSharedPreferences("quantic.Quran",
Context.MODE_PRIVATE);
recitorID = prefs.getInt("recID", -1);
playpos = prefs.getInt("posPlaying", -1);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
final ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.song_item, parent, false);
ImageView download = (ImageView) vi
.findViewById(R.id.playlist_item_download);
db.openDB();
if (db.isDownloaded(data.get(position).getNumber(), data.get(position)
.getRecitorName(), data.get(position).getRecitorID()))
download.setImageResource(R.drawable.download_yes);
else {
download.setImageResource(R.drawable.download_no);
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DownloadFileFromURL(activity, data.get(position)
.getRecitorName(), data.get(position).getTitle(),
data.get(position).getLink(), data.get(position)
.getNumber(), data.get(position)
.getRecitorID()).execute();
if (!db.isDBOpen())
db.openDB();
db.addDownloaded(data.get(position).getNumber(),
data.get(position).getLink(), 0, data.get(position)
.getRecitorID(), "", data.get(position)
.getTitle());
Toast.makeText(activity,
"Downloading " + data.get(position).getTitle(),
Toast.LENGTH_SHORT).show();
}
});
}
db.closeDB();
TextView number = (TextView) vi.findViewById(R.id.playlist_item_num);
TextView reciterName = (TextView) vi
.findViewById(R.id.playlist_item_reciterName);
reciterName.setText(data.get(position).getRecitorName());
if (activity.getClass() == Playlist.class) {
reciterName.setVisibility(View.GONE);
}
TextView title = (TextView) vi.findViewById(R.id.playlist_item_reciter);
title.setText(data.get(position).getTitle());
number.setText((position + 1) + "");
ImageView eq = (ImageView) vi.findViewById(R.id.playlist_item_equlizer);
if (Tplayer.getInstance().isPlaying())
if (Tplayer.getInstance().getPosition() == position
&& data.get(position).getRecitorID() == Tplayer
.getInstance().getSong().getRecitorID()) {
eq.setVisibility(View.VISIBLE);
Ion.with(eq).load("http://darkodev.info/quran/dots.gif");
} else {
eq.setVisibility(View.GONE);
}
return vi;
}
}
Very old question, but no answer. I'm sure you have found a fix by now, but anyway.
You're changing the songs list object in background, and if Android decides to redraw your list (user scrolls your list), effectively accessing the songs list object, it may have changed and cause this exception to be thrown.
You need to use a temporary songs list and create a new adapter with it to update your list, thus not changing the current adapter list until you set a new adapter from the main UI thread.
i am trying to filter the listview using edit text at the top but it providing null pointer exception in the adapter2.filter(text) of add text changed listener . please provide me some suggestion`
Here is my edit text`
friendsList.setAdapter(new FriendListAdapter(this));
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
System.out.println("test=="+text);
adapter2.filter(text);
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
//adapter.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
Here is my adapter
public class FriendListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
FriendsList friendsList;
Context context;
ViewHolder holder;
private boolean userSelected = false;
private RadioButton mCurrentlyCheckedRB;
private int mResourceId = 0;
private LayoutInflater mLayoutInflater;
private RadioButton mSelectedRB;
private int mSelectedPosition = -1;
public FriendListAdapter(FriendsList friendsList) {
this.friendsList = friendsList;
if (Utility.model == null) {
Utility.model = new FriendsGetProfilePics();
}
Utility.model.setListener(this);
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
#Override
public int getCount() {
return jsonArray.length();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewgroup) {
JSONObject jsonObject = null;
Model model = (Model) getItem(position);
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e1) {
e1.printStackTrace();
}
View hView = convertView;
if (convertView == null) {
hView = mInflater.inflate(R.layout.friend_item, null);
ViewHolder holder = new ViewHolder();
holder.profile_pic = (ImageView) hView
.findViewById(R.id.profile_pic);
holder.name = (TextView) hView.findViewById(R.id.name);
holder.info = (TextView) hView.findViewById(R.id.info);
holder.radiobt = (RadioButton) hView.findViewById(R.id.radio);
hView.setTag(holder);
}
ViewHolder holder = (ViewHolder) hView.getTag();
if (position == getCount() - 1 && userSelected == false) {
holder.radiobt.setChecked(true);
mCurrentlyCheckedRB = holder.radiobt;
} else {
holder.radiobt.setChecked(false);
}
holder.radiobt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if((position != mSelectedPosition && mSelectedRB != null)){
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton)v;
System.out.println("onItemClick ");
try {
if (graph_or_fql.equals("graph")) {
System.out.println("in if loop ");
friendId = jsonArray.getJSONObject(position).getLong("id");
image = jsonArray.getJSONObject(position).getString("picture");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
} else {
System.out.println("in else loop ");
friendId = jsonArray.getJSONObject(position).getLong("uid");
image = jsonArray.getJSONObject(position).getString(
"pic_square");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
}
check = true;
name = jsonArray.getJSONObject(position).getString("name");
Toast.makeText(getApplicationContext(), "You Selected : " + name,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
}
}
});
if(mSelectedPosition != position){
holder.radiobt.setChecked(false);
}else{
holder.radiobt.setChecked(true);
if(mSelectedRB != null && holder.radiobt != mSelectedRB){
mSelectedRB = holder.radiobt;
}
}
try {
if (graph_or_fql.equals("graph")) {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("id"),
jsonObject.getString("picture")));
} else {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("uid"),
jsonObject.getString("pic_square")));
}
} catch (JSONException e) {
holder.name.setText("");
}
try {
holder.name.setText(jsonObject.getString("name"));
} catch (JSONException e) {
holder.name.setText("");
}
try {
if (graph_or_fql.equals("graph")) {
holder.info.setText(jsonObject.getJSONObject("location")
.getString("name"));
} else {
JSONObject location = jsonObject
.getJSONObject("current_location");
holder.info.setText(location.getString("city") + ", "
+ location.getString("state"));
}
} catch (JSONException e) {
holder.info.setText("");
}
return hView;
}
// Filter Class
public void filter(String charText) {
System.out.println("in adapter filter");
charText = charText.toLowerCase(Locale.getDefault());
System.out.println("1");
rowitems.clear();
System.out.println("2");
if (charText.length() == 0) {
System.out.println("3");
rowitems.addAll(listData);
} else {
for (Model wp : listData) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
rowitems.add(wp);
}
}
}
notifyDataSetChanged();
}
private class ViewHolder {
ImageView profile_pic;
TextView name;
TextView info;
// CheckBox check;
RadioButton radiobt;
}
}
Here is my main activity
public class FriendsList extends Activity implements OnItemClickListener{
private Handler mHandler;
public static Long friendId;
public static String name = "";
protected ListView friendsList;
protected static JSONArray jsonArray;
protected String graph_or_fql;
public Button bt;
public static String image = "0";
public boolean check = false;
public static String freind_id = "";
public boolean select = false;
public RadioButton radiobtn;
public ListView friendList;
private List<Model> rowitems=null;
ArrayList<Model> listData;
AdapterList adapter;
EditText search;
FriendListAdapter adapter2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.friends_list);
//radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
bt = (Button) findViewById(R.id.com_facebook_picker_done_button);
radiobtn = (RadioButton) findViewById(R.id.radio);
search=(EditText) findViewById(R.id.editText100);
Bundle extras = getIntent().getExtras();
String apiResponse = extras.getString("API_RESPONSE");
graph_or_fql = extras.getString("METHOD");
try {
if (graph_or_fql.equals("graph")) {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
} else {
jsonArray = new JSONArray(apiResponse);
}
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
return;
}
friendsList = (ListView) findViewById(R.id.friends_list);
// friendsList.setAdapter(new FriendListAdapter(this));
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);
friendsList.setOnItemClickListener(this);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter2.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
i am passing the facebook friend list to the listview.please provide some suggestion
Thanks in advance
For filter the listview using edit text at the top .
I used this code.
Make one list called searchResults than in onTextChanged method of edittext simply do this-
String searchString = `your edittext object`.getText().toString();
int textLength = searchString.length();
searchResults.clear();
for (int i = 0; i < `your main list of items`.size(); i++) {
String name = `your main list of items`.get(i).get("`your key`").toString();
System.out.println(" name " + name);
if (textLength <= title.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(name.substring(0, textLength))) {
searchResults.add(`your main list of items`.get(i));
System.out.println("the array list is "+ `your main list of items`.get(i));
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
}
}
if (searchResults.isEmpty()) {
Toast toast = Toast.makeText(getApplicationContext(),"No Items Matched",Toast.LENGTH_SHORT);
toast.show();
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
mAdapter.notifyDataSetChanged();
and on setOnItemClickListener just check searchResults.isEmpty() if true than use your your main list of items and if false than use searchResults list.
May be it will help you.try this.
change your filter with following code:
#Override
public Filter getFilter() {
//Log.d("in filter", "yes");
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
and set your list in this function and after set your list :
oReturn.values = YourList;
and finall
return oReturn;
and in Your search.addTextChangedListener(new TextWatcher()) just in onTextChanged add following line:
adapter2.getFilter().filter(s.toString());
Try this,
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);