Viewpager, Cursor and Fragment - android

I am new to the viewpager and was wondering if anyone could point me to a tutorial or source code of a project that uses a viewpager with fragments and a database. I've seen examples of PagerAdapters but I'm just not getting how they all work together (Cursor, Fragment and PagerAdapter)
Thanks in advance.

I have posted some answers in the other posts related to your question.
Here's some of the links that you might find helpful.
First Link: To get custom views in every page slide. (Accepted answer)
Android:How to create different view in ViewPager?
Second: How to properly use fragments with ViewPager. (Accepted answer)
How to properly use fragments with ViewPager?
If those two links are not that helpful, try this:
public class AllActivities extends FragmentActivity implements ActionBar.TabListener {
public ViewPager viewPager;
private AllPagesAdapter mAdapter;
private ActionBar actionBar;
private String [] tabs = {"Android","CoreJava","J2EE","Database","Web Services"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing all stuff
viewPager = (ViewPager)findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new AllPagesAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Add the tabs here
for(String tab_name:tabs){
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position){
//on Page change, that particular page should be selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0,float arg1,int arg2){
}
#Override
public void onPageScrollStateChanged(int position){
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
}
//This is one of the fragment and assume that Expandablelistview is your list view.. In both the cases, i am setting the adapter in the onActivityCreated() method.
public class Android extends android.support.v4.app.Fragment {
ExpandableListAdapter listAdapter;
// private ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
ListView lv1;
private static final String QUESTION = "question";
private static final String ANSWERS = "answer";
// ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mikeview = inflater.inflate(R.layout.androidlayout, container, false);
return mikeview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ExpandableListView expListView = null;
try{
expListView = (ExpandableListView) getActivity().findViewById(R.id.androidExpandableList);
}
catch (Exception e){
e.printStackTrace();
}
new Thread(){
#Override
public void run(){
}
}.start();
try {
setParent();
prepareChild();
} catch (Exception e) {
e.printStackTrace();
}
ExpandableListAdapter listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
/*Toast.makeText(
getActivity(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();*/
return true;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
/* Toast.makeText(getActivity(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();*/
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
/*Toast.makeText(getActivity(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();*/
}
});
}
public void setParent(){
listDataHeader = new ArrayList<String>();
try{
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray array = json.getJSONArray("androidquestion");
for(int my =0;my<array.length();my++){
JSONObject c = array.getJSONObject(my);
String topics = c.getString(QUESTION);
listDataHeader.add(topics);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
public void prepareChild() throws JSONException {
listDataChild = new HashMap<String, List<String>>();
try{
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray array = json.getJSONArray("androidquestion");
for(int mz = 0;mz<array.length();mz++){
ArrayList<String> child = new ArrayList<String>();
JSONObject d = array.getJSONObject(mz);
String ans = d.getString(ANSWERS);
child = new ArrayList<String>();
child.add(ans);
int position = mz ;
listDataChild.put(listDataHeader.get( position),child);
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("android.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
//This is the adapter.
public class AllPagesAdapter extends FragmentStatePagerAdapter {
public AllPagesAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Android();
case 1:
return new CoreJava();
case 2:
return new J2EE();
case 3:
return new Database();
case 4:
return new WebServices();
}
return null;
}
#Override
public int getCount() {
return 5;
}
}
//This is the adapter for my expandable list view.. in your case, your can just use the listadapter or any other adapter you want to use. This is just an optional part.
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newlistitems,null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.newlistviewitems);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater myInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = myInflater.inflate(R.layout.newlistgroup, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.newlistviewgroup);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Lemme know if you need some more examples on that..:)

You need to create abstract class adapter to use both cursor and pager adapter and extend to your own adapter and bind the view.
public abstract class CursorPagerAdapter extends PagerAdapter {
public static final String TAG = CursorPagerAdapter.class.getSimpleName();
protected WeakReference<Context> ctxRef;
protected boolean mDataValid;
protected boolean mAutoRequery;
protected Cursor mCursor;
protected int mRowIDColumn;
protected ChangeObserver mChangeObserver;
protected DataSetObserver mDataSetObserver;
/**
* If set the adapter will call requery() on the cursor whenever a content change notification is
* delivered. Implies {#link #FLAG_REGISTER_CONTENT_OBSERVER}.
*
* #deprecated This option is discouraged, as it results in Cursor queries being performed on the
* application's UI thread and thus can cause poor responsiveness or even Application
* Not Responding errors. As an alternative, use {#link android.app.LoaderManager} with
* a {#link android.content.CursorLoader}.
*/
#Deprecated
public static final int FLAG_AUTO_REQUERY = 0x01;
/**
* If set the adapter will register a content observer on the cursor and will call {#link
* # onContentChanged()} when a notification comes in. Be careful when using this flag: you will
* need to unset the current Cursor from the adapter to avoid leaks due to its registered
* observers. This flag is not needed when using a CursorAdapter with a {#link
* android.content.CursorLoader}.
*/
public static final int FLAG_REGISTER_CONTENT_OBSERVER = 0x02;
public CursorPagerAdapter(Context context, Cursor c, int flags) {
init(context, c, flags);
}
void init(Context context, Cursor c, int flags) {
if ((flags & FLAG_AUTO_REQUERY) == FLAG_AUTO_REQUERY) {
flags |= FLAG_REGISTER_CONTENT_OBSERVER;
mAutoRequery = true;
} else {
mAutoRequery = false;
}
boolean cursorPresent = c != null;
mCursor = c;
mDataValid = cursorPresent;
ctxRef = new WeakReference<>(context);
mRowIDColumn = cursorPresent ? c.getColumnIndexOrThrow("_id") : -1;
if ((flags & FLAG_REGISTER_CONTENT_OBSERVER) == FLAG_REGISTER_CONTENT_OBSERVER) {
mChangeObserver = new ChangeObserver();
mDataSetObserver = new MyDataSetObserver();
} else {
mChangeObserver = null;
mDataSetObserver = null;
}
if (cursorPresent) {
if (mChangeObserver != null) {
c.registerContentObserver(mChangeObserver);
}
if (mDataSetObserver != null) {
c.registerDataSetObserver(mDataSetObserver);
}
}
}
public Cursor getCursor() {
return mCursor;
}
#Override
public int getCount() {
if (mDataValid && mCursor != null)
return mCursor.getCount();
else
return 0;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (!mDataValid) {
throw new IllegalStateException("this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
Context context = ctxRef.get();
if (context != null) {
View v = newView(context, mCursor, (ViewGroup) container);
bindView(v, context, mCursor);
((ViewPager) container).addView(v);
return v;
} else {
throw new IllegalStateException("context is null");
}
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
public abstract View newView(Context context, Cursor cursor, ViewGroup parent);
public abstract void bindView(View view, Context context, Cursor cursor);
public void changeCursor(Cursor cursor) {
Cursor old = swapCursor(cursor);
if (old != null) {
old.close();
}
}
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) return null;
Cursor oldCursor = mCursor;
if (oldCursor != null) {
if (mChangeObserver != null) {
oldCursor.unregisterContentObserver(mChangeObserver);
}
if (mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
}
mCursor = newCursor;
if (newCursor != null) {
if (mChangeObserver != null) {
newCursor.registerContentObserver(mChangeObserver);
}
if (mDataSetObserver != null) {
newCursor.registerDataSetObserver(mDataSetObserver);
}
mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
mDataValid = true;
// notify the observers about the new cursor
notifyDataSetChanged();
} else {
mRowIDColumn = -1;
mDataValid = false;
notifyDataSetChanged();
}
return oldCursor;
}
private void onContentChange() {
if (mAutoRequery && mCursor != null && !mCursor.isClosed()) {
mDataValid = mCursor.requery();
}
}
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(new Handler());
}
/**
*
* #return True if self-change notifications should be delivered to the observer.
*/
#Override
public boolean deliverSelfNotifications() {
return true;
}
/**
* This method is called when a content change occurs.
* #param selfChange
*/
#Override
public void onChange(boolean selfChange) {
onContentChange();
}
}
private class MyDataSetObserver extends DataSetObserver {
#Override
public void onChanged() {
mDataValid = true;
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
mDataValid = false;
notifyDataSetChanged();
}
}
}
Sample Adapter (in kotlin):
class SampleAdapter(context: Context, cursor: Cursor?, autoQuery: Int): CursorPagerAdapter(context, cursor, autoQuery) {
internal var mContext: Context
internal var mLayoutInflater: LayoutInflater
internal var aQuery: AQuery
val imageWidth = Helper.getDisplayWidth(context)
init {
mContext = context
mLayoutInflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
aQuery = AQuery(context)
}
override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View {
return mLayoutInflater.inflate(R.layout.your_item_row, parent, false)
}
override fun bindView(view: View?, context: Context?, cursor: Cursor?) {
val sampleVo = SampleVo.getValueFromCursor(cursor)
val tvTitle = view?.findViewById<AppCompatTextView>(R.id.tvTitle)
tvTitle?.text = sampleVo.title
}
Original Source: link

Related

How to replace the baseadapter value and how to stop the pagination loading in android filter screen?

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.

Replacing Fragment in ViewPager shows blank screen?

I'm having a lot of trouble getting Fragments to work with Tabs/Swiping. I have one activity and two Fragments, one which has a ListView. What I want is when I swipe from fragment 1 to the fragment with the ListView, to refresh the ListView or if possible recreate the second fragment....
What I am trying right now is to use FragmentTransaction.replace() like this:
public void onTabSelected(Tab arg0, android.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
Fragment frag = new FragmentTwo();
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
if (arg0.getPosition() == 1) {
trans.replace(R.id.pager, frag);
trans.addToBackStack(null);
trans.commit();
}
}
So I thought that when I swipe to tab 2, which is the one with the ListView, it would replace it with a new one, which it creates. What is actually happening is that when I swipe to tab 2, it recreates the fragment with the ListView (I know because I have a dialog in the onCreateView which shows to the screen) but then the fragment/tab is blank/black. What am I doing wrong? Where does this fragment which is created go?
I don't know if the code of the fragments is relevant but please let me know if I should post it and I can do that. This is my PagerAdapter class.
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
case 2:
return new FragmentThree();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
Thanks for any help! I'm really pulling my hair out over this one :(
Edit:
When you swipe from tab 1 to tab 2, tab 2 shows my dialog and then loads the tab, but if I go back to tab 1 its all black...and if I then go to tab 2 again, it creates again and shows my dialog and then goes black as well...
Edit: (adding listview fragment code)
public class FragmentTwo extends Fragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser_Helpers2 jParser = new JSONParser_Helpers2();
ArrayList<HashMap<String, String>> tripList;
// url to get all products list
private static String url_all_trips = "http://10.0.2.2/android_connect/get_all_trips.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TRIPS = "trips";
private static final String TAG_TRIPID = "tripid";
private static final String TAG_TRIPNAME = "tripName";
private static final String TAG_UID = "uid32";
// products JSONArray
JSONArray trips = null;
View rootView;
Button btnRefresh;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_one, container, false);
rootView = inflater.inflate(R.layout.fragment_two, container, false);
btnRefresh = (Button) rootView.findViewById(R.id.refresh);
// Hashmap for ListView
tripList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = (ListView) rootView.findViewById(R.id.list);
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//getting values from selected ListItem
String tripid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
//starting new intent
Intent in = new Intent(getActivity(), EditTrip_Activity.class);
//sending pid to next activity
in.putExtra(TAG_TRIPID, tripid);
//starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
return rootView;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
ListView lv = (ListView) rootView.findViewById(R.id.list);
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading your trips. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_trips, "GET", params);
// Check your log cat for JSON response
Log.d("All Trips: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
trips = json.getJSONArray(TAG_TRIPS);
// looping through All Products
for (int i = 0; i < trips.length(); i++) {
JSONObject c = trips.getJSONObject(i);
// Storing each json item in variable
String tripid = c.getString(TAG_TRIPID);
String tripname = c.getString(TAG_TRIPNAME);
String userId = c.getString("uid");
// creating new HashMap
DatabaseHandler_Helpers db = new DatabaseHandler_Helpers(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
if (userId.equals(db.getUserDetails().get("uid"))) {
// adding each child node to HashMap key => value
map.put(TAG_TRIPID, tripid);
map.put(TAG_TRIPNAME, tripname);
// adding HashList to ArrayList
tripList.add(map);
} //else {
//map.put(TAG_TRIPID, "");
//map.put(TAG_TRIPNAME, "You have no tracked trips.");
//tripList.add(map);
//}
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity(),
NewTrip_Activity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
((Activity) getActivity()).runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), tripList,
R.layout.list_item, new String[] { TAG_TRIPID,
TAG_TRIPNAME},
new int[] { R.id.pid, R.id.name });
// updating listview
((ListView) lv.findViewById(R.id.list)).setAdapter(adapter);
}
});
}
}
}
Try to extend FragmentStatePagerAdapter instead of FragmentPagerAdapter.
Here's my code for fragments and it works fine for me:
//Adapter
public class AllPagesAdapter extends FragmentStatePagerAdapter {
public AllPagesAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Android();
case 1:
return new CoreJava();
case 2:
return new J2EE();
case 3:
return new Database();
case 4:
return new WebServices();
}
return null;
}
#Override
public int getCount() {
return 5;
}
}
//For example, this is one fragment:
public class Database extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View databaseview = inflater.inflate(R.layout.database, container, false);
return databaseview;
}
}
//My MainActivity
public class AllActivities extends FragmentActivity implements ActionBar.TabListener {
public ViewPager viewPager;
private AllPagesAdapter mAdapter;
private ActionBar actionBar;
private String [] tabs = {"Android","CoreJava","J2EE","Database","Web Services"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing all stuff
viewPager = (ViewPager)findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new AllPagesAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Add the tabs here
for(String tab_name:tabs){
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position){
//on Page change, that particular page should be selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0,float arg1,int arg2){
}
#Override
public void onPageScrollStateChanged(int position){
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
}
Let me know if you also want the implementation of the listview in any one fragment.
Hope this helps..:)
My children fragments are in a ViewPager. I just replace the ViewPage adapter by FragmentStatePagerAdapter instead of FragmentPagerAdapter
Child Fragment
....
mViewPager.setAdapter(new SearchOriginTabsPagerAdapter(getFragmentManager()));
Adapter...
public class SearchOriginTabsPagerAdapter extends FragmentStatePagerAdapter {
public SearchOriginTabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new NearbyFragment();
case 1:
return new RecentOriginFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
Alright.. Here's the thing..
I didn't really use your code but used similar concept. Its gonna be a complete solution.
//This is the starting point of the app. It has many fragments and I am using my own json to get the data.
public class AllActivities extends FragmentActivity implements ActionBar.TabListener {
public ViewPager viewPager;
private AllPagesAdapter mAdapter;
private ActionBar actionBar;
private String [] tabs = {"Android","CoreJava","J2EE","Database","Web Services"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing all stuff
viewPager = (ViewPager)findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new AllPagesAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Add the tabs here
for(String tab_name:tabs){
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position){
//on Page change, that particular page should be selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0,float arg1,int arg2){
}
#Override
public void onPageScrollStateChanged(int position){
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
}
//This is one of the fragment and assume that Expandablelistview is your list view.. In both the cases, i am setting the adapter in the onActivityCreated() method.
public class Android extends android.support.v4.app.Fragment {
ExpandableListAdapter listAdapter;
// private ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
ListView lv1;
private static final String QUESTION = "question";
private static final String ANSWERS = "answer";
// ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mikeview = inflater.inflate(R.layout.androidlayout, container, false);
return mikeview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ExpandableListView expListView = null;
try{
expListView = (ExpandableListView) getActivity().findViewById(R.id.androidExpandableList);
}
catch (Exception e){
e.printStackTrace();
}
new Thread(){
#Override
public void run(){
}
}.start();
try {
setParent();
prepareChild();
} catch (Exception e) {
e.printStackTrace();
}
ExpandableListAdapter listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
/*Toast.makeText(
getActivity(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();*/
return true;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
/* Toast.makeText(getActivity(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();*/
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
/*Toast.makeText(getActivity(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();*/
}
});
}
public void setParent(){
listDataHeader = new ArrayList<String>();
try{
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray array = json.getJSONArray("androidquestion");
for(int my =0;my<array.length();my++){
JSONObject c = array.getJSONObject(my);
String topics = c.getString(QUESTION);
listDataHeader.add(topics);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
public void prepareChild() throws JSONException {
listDataChild = new HashMap<String, List<String>>();
try{
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray array = json.getJSONArray("androidquestion");
for(int mz = 0;mz<array.length();mz++){
ArrayList<String> child = new ArrayList<String>();
JSONObject d = array.getJSONObject(mz);
String ans = d.getString(ANSWERS);
child = new ArrayList<String>();
child.add(ans);
int position = mz ;
listDataChild.put(listDataHeader.get( position),child);
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("android.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
//This is the adapter.
public class AllPagesAdapter extends FragmentStatePagerAdapter {
public AllPagesAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Android();
case 1:
return new CoreJava();
case 2:
return new J2EE();
case 3:
return new Database();
case 4:
return new WebServices();
}
return null;
}
#Override
public int getCount() {
return 5;
}
}
//This is the adapter for my expandable list view.. in your case, your can just use the listadapter or any other adapter you want to use. This is just an optional part.
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newlistitems,null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.newlistviewitems);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater myInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = myInflater.inflate(R.layout.newlistgroup, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.newlistviewgroup);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
If anyone using viewpager2 then use the below constructor.
FragmentStateAdapter(fragmentManager, lifecycle)

How to perform search in the expandable listview which is in the fragment?

Here is the thing..
I have one activity in which i have implmented the ActionBarSherlock,View Pager with Tab Navigation.
In Action Bar i have placed the search view.Now i am adding the list of fragments from the activity using viewPagerAdapter.
Now, In fragments i have placed the expandable listview and i am display the products with its section name in the expandable listview.
What i want to do ::
I want to perform the search of products from the expandable listview.
Problem which i have faced ::
I have placed the searchview in the Activity from which i am calling the different fragments.So how to perform the search ???
My code ::
Activity ::
public class Activity extends SherlockFragmentActivity implements TabListener,SearchView.OnQueryTextListener,SearchView.OnSuggestionListener
{
TabHost tabHost;
TabHost.TabSpec spec;
Intent intent;
Resources res;
Context mContext;
ProgressDialog pd=null;
Handler handler=new Handler();
MD5Generator md5Generator=new MD5Generator();
HttpConn httpConn=new HttpConn();
MyAccountInfo myAccountInfo;
private UserInfo userInfo=new UserInfo();
private Calendar cal = Calendar.getInstance();
private AppPreferences preference;
ArrayList<String> menuInfo;
//private ActionBar actionBar;
private ActionBarTabMenuAdapter actionbartabmenuAdapter;
private ViewPager awesomePager;
DataHelper dataHelper;
ArrayList<Integer> servicesImage;
ArrayList<String> servicesName;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ActionBar actionBar=getSupportActionBar();
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mContext=this;
// getSupportActionBar().setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.white)));
// getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// getSupportActionBar().setDisplayUseLogoEnabled(false);
// getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header_color)));
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
dataHelper=new DataHelper(this);
menuInfo=dataHelper.getTransMenuInfo();
servicesName = new ArrayList<String>();
servicesImage = new ArrayList<Integer>();
if(menuInfo.contains("1"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("1"));
servicesImage.add(R.drawable.abs__ic_search);
}
if(menuInfo.contains("2"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("2"));
servicesImage.add(R.drawable.abs__ic_search);
}
if(menuInfo.contains("4"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("4"));
servicesImage.add(R.drawable.abs__ic_search);
}
dataHelper.close();
servicesName.add("My Account");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("myacc");
servicesName.add("Reports");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("Reports");
servicesName.add("Settings");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("Settings");
List<Fragment> fragments = getFragments();
actionbartabmenuAdapter = new ActionBarTabMenuAdapter(getSupportFragmentManager(), fragments,this,servicesName,servicesImage);
awesomePager.setAdapter(actionbartabmenuAdapter);
System.out.println(" **** Selected Item==>"+awesomePager.getCurrentItem());
awesomePager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
for (int i = 0; i < actionbartabmenuAdapter.getCount(); i++) {
Tab tab = actionBar.newTab();
//tab.setText(awesomeAdapter.getPageTitle(i));
tab.setText(servicesName.get(i));
tab.setIcon(servicesImage.get(i));
tab.setTabListener(this);
actionBar.addTab(tab);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Code Comes here...
System.out.println("Key Event:"+event.getAction()+",keyCode"+keyCode);
onBackPressed();
return true;
}
private List<Fragment> getFragments()
{
List<Fragment> fList = new ArrayList<Fragment>();
if(menuInfo.contains("1"))
{
fList.add(TopUpFragment.newInstance(this,"Topup"));
}
if(menuInfo.contains("2"))
{
fList.add(BillPayFragment.newInstance(this,"Billpay"));
}
if(menuInfo.contains("4"))
{
fList.add(VoucherFragment.newInstance(this,"Voucher Sell"));
}
fList.add(MyAccountFragment.newInstance(this,"My Account"));
fList.add(ReportFragment.newInstance(this,"Reports"));
fList.add(SettingsListFragment.newInstance(this,"Settings"));
return fList;
}
#Override
public void onBackPressed()
{
new AlertDialog.Builder(ButtonPayActivity.this)
.setTitle( "Exit Application" )
.setMessage( "Are you sure you want to Exit" )
.setPositiveButton("YES", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of YES
finish();
}
})
.setNegativeButton("NO", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of CANCEL
arg0.dismiss();
}
}).show();
}
public static View prepareTabView(Context context, String text,int resId) {
View view = LayoutInflater.from(context).inflate(
R.layout.custom_tabview, null);
ImageView iv = (ImageView) view.findViewById(R.id.iv_tabimage);
iv.setImageResource(resId);
TextView tv = (TextView) view.findViewById(R.id.tabIndicatorTextView);
tv.setText(text);
return view;
}
private class ActionBarTabMenuAdapter extends FragmentPagerAdapter {
Activity context;
Context ctx;
ArrayList<String> menuInfo;
private List<Fragment> fragments;
ArrayList<String> services;
ArrayList<Integer> images;
public ActionBarTabMenuAdapter(FragmentManager fm, List<Fragment> fragments,Context ctx,ArrayList<String> servicesName,ArrayList<Integer> servicesImage)
{
super(fm);
this.context=(Activity) ctx;
dataHelper=new DataHelper(ctx);
menuInfo=dataHelper.getTransMenuInfo();
dataHelper.close();
this.services = servicesName;
this.images = servicesImage;
this.fragments = fragments;
menuInfo.add("My Account");
menuInfo.add("Reports");
menuInfo.add("Settings");
System.out.println("## Ctx in ButtonPay==>"+this.context);
}
#Override
public int getCount()
{
return menuInfo.size();
}
#Override
public Fragment getItem(int position) {
System.out.println("position of fragment--"+position);
return this.fragments.get(position);
}
}
class ViewHolder {
TextView Title, Description, ReadMore;
}
public void onClick(View v) {
}
#Override
public void onTabReselected(Tab tabposition, FragmentTransaction fragmentposition) {
System.out.println("Tab Reselected method");
}
#Override
public void onTabSelected(Tab tabposition, FragmentTransaction fragmentposition) {
awesomePager.setCurrentItem(tabposition.getPosition());
}
#Override
public void onTabUnselected(Tab tabposition, FragmentTransaction fragmentposition) {
System.out.println("Tab unselected method");
System.out.println("tab posiiton in unselected method---"+tabposition.getPosition());
System.out.println("fragment position in unselected method---"+tabposition);
}
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_item_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search for Products");
searchView.setOnQueryTextListener(this);
searchView.setOnSuggestionListener(this);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(this, "You searched for: " + query, Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
#Override
public boolean onSuggestionClick(int position) {
Toast.makeText(this, "Suggestion clicked: ",Toast.LENGTH_LONG).show();
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_Home:
startActivityForResult(new Intent(ButtonPayActivity.this,ButtonPayActivity.class), 11);
break;
case R.id.menu_favourite:
finish();
startActivityForResult(new Intent(ButtonPayActivity.this,FavouriteMenuActivity.class), 11);
break;
case R.id.menu_Balance:
new Thread(new GetBalanceInfoRunnable(mContext)).start();
break;
case R.id.menu_logout:
new AlertDialog.Builder(ButtonPayActivity.this)
.setTitle( "Exit Application")
.setMessage( "Are you sure you want to Logout?")
.setPositiveButton("YES", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of YES
setResult(2);
finish();
}
})
.setNegativeButton("NO", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of CANCEL
arg0.dismiss();
}
}).show();
break;
}
return super.onOptionsItemSelected(item);
}
}
Fragment ::
public class TopUpFragment extends SherlockFragment
{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
LinkedHashMap<String,String>listHeader;
ArrayList<String> topupProSectionID;
ArrayList<String> topupProSectionsName;
ArrayList<TopupProSectionName.Products> listDataChild;
static Context ctx;
static TopUpFragment f ;
private DataHelper dataHelper;
private int lastExpandedPosition = -1;
private ArrayList<TopupProSectionName> mTopupGroupCollection;
public static TopUpFragment newInstance(Activity context,String string)
{
f = new TopUpFragment();
ctx=context;
System.out.println("$$$ onNewInst==>"+ctx);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
//String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
//TextView messageTextView = (TextView)v.findViewById(R.id.textView);
//messageTextView.setText(message);
expListView = (ExpandableListView)v.findViewById(R.id.lvExp);
prepareListData();
System.out.println("%%% Ctx==>"+ctx);
return v;
}
private void prepareListData()
{
listHeader = new LinkedHashMap<String, String>();
dataHelper=new DataHelper(ctx);
topupProSectionID=new ArrayList<String>();
listHeader = dataHelper.getSectionSForTopupProduct();
if (listHeader != null)
{
Map.Entry me = null;
Set entrySet = listHeader.entrySet();
Iterator i = entrySet.iterator();
mTopupGroupCollection = new ArrayList<TopupProSectionName>();
TopupProSectionName sectionName = null;
TopupProSectionName.Products topupProduct = null;
while (i.hasNext())
{
sectionName = new TopupProSectionName();
me = (Map.Entry)i.next();
System.out.print("-->"+me.getKey() + ": ");
System.out.println(me.getValue());
sectionName.setsectionName((String)me.getKey());
listDataChild=new ArrayList<TopupProSectionName.Products>();
listDataChild=dataHelper.getFlexiProducts(me.getValue().toString());
listDataChild=dataHelper.getFixProducts(me.getValue().toString(),listDataChild);
System.out.println("Getting products for sys ser ID:"+me.getValue().toString());
//billpayProSectionsName.add((String) me.getKey());
topupProSectionID.add((String) me.getValue());
for(int index=0;index<listDataChild.size();index++)
{
topupProduct = sectionName.new Products();
if(listDataChild.get(index).getSystemServiceID().equals(me.getValue()))
{
topupProduct.setProductName(listDataChild.get(index).getProductName());
topupProduct.setProductID(listDataChild.get(index).getProductID());
sectionName.topupProductList.add(topupProduct);
}
}
mTopupGroupCollection.add(sectionName);
}
}
dataHelper.close();
listAdapter = new ExpandableListAdapter(ctx,mTopupGroupCollection,expListView);
expListView.setAdapter(listAdapter);
}
class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private ArrayList<TopupProSectionName> listDataHeader; // header titles
ArrayList<TopupProSectionName.Products> topupProducts;
private int[] groupStatus;
private ExpandableListView mExpandableListView;
public ExpandableListAdapter(Context context,
ArrayList<TopupProSectionName>sectionName,ExpandableListView pExpandableListView)
{
this._context = context;
this.listDataHeader = sectionName;
this.topupProducts = listDataChild;
mExpandableListView = pExpandableListView;
groupStatus = new int[listDataHeader.size()];
setListEvent();
}
private void setListEvent()
{
mExpandableListView.setOnGroupExpandListener(new OnGroupExpandListener()
{
public void onGroupExpand(int groupPosition)
{
//collapse the old expanded group, if not the same as new group to expand
//groupStatus[position] = 1;
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition)
{
mExpandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
/*mExpandableListView.setOnGroupCollapseListener(new OnGroupCollapseListener()
{
#Override
public void onGroupCollapse(int position)
{
groupStatus[position] = 0;
}
});*/
mExpandableListView.setOnChildClickListener(new OnChildClickListener()
{
#Override
public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id)
{
String ID=listDataHeader.get(groupPosition).topupProductList.get(childPosition).getProductID();
System.out.println("Product ID in Adapter==>"+ID);
return true;
}
});
}
#Override
public String getChild(int groupPosition, int childPosititon) {
return listDataHeader.get(groupPosition).topupProductList.get(childPosititon).getProductName();
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ChildHolder childHolder;
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item_fragment, null);
childHolder = new ChildHolder();
childHolder.title = (TextView) convertView.findViewById(R.id.lblListItem);
convertView.setTag(childHolder);
}
else
{
childHolder = (ChildHolder) convertView.getTag();
}
childHolder.title.setText(mTopupGroupCollection.get(groupPosition).topupProductList.get(childPosition).getProductName());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return mTopupGroupCollection.get(groupPosition).topupProductList.size();
}
#Override
public Object getGroup(int groupPosition) {
return mTopupGroupCollection.get(groupPosition);
}
#Override
public int getGroupCount() {
return mTopupGroupCollection.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
{
GroupHolder groupHolder;
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
groupHolder = new GroupHolder();
groupHolder.title = (TextView) convertView.findViewById(R.id.lblListHeader);
convertView.setTag(groupHolder);
}
else
{
groupHolder = (GroupHolder) convertView.getTag();
}
groupHolder.title.setTypeface(null, Typeface.BOLD);
groupHolder.title.setText(mTopupGroupCollection.get(groupPosition).getsectionName());
return convertView;
}
class GroupHolder {
TextView title;
}
class ChildHolder {
TextView title;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
I am actually getting the action bar in wrong way.
TO use the action bar in each fragment ::
i have placed the setHasOptionsMenu(true); in my onCreate() of fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
After that i am able to use the onCreateOptionMenu() in which i placed the searchview and now i am able to search the date from the expandable listview,getting text from searchview.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu);
final MenuItem searchItem = menu.findItem(R.id.menu_item_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Here");
}
And now m done,Problem resolved.... ;)

How to apply filter to customlistview

I am using Custom adapter for my listview and I want to apply filter for searching perticular item from the list how to do that? I Know that how to do that for adapter extending ArrayAdapter but in my case it is simplesectionadapter.I have one editText above the listview from the text entered in the edittext I want to serch the Item.
Collections.sort(contents, new Comparator<CategoryPojo>() {
#Override
public int compare(CategoryPojo s1, CategoryPojo s2) {
return s1.getCategoryName().compareToIgnoreCase(
s2.getCategoryName());
}
});
final CategoryAdapter adapter = new CategoryAdapter(this,
android.R.layout.simple_list_item_1, contents);
Sectionizer<CategoryPojo> alphabetSectionizer = new Sectionizer<CategoryPojo>() {
#Override
public String getSectionTitleForItem(CategoryPojo instance) {
return instance.getCategoryName().substring(0, 1);
}
};
final SimpleSectionAdapter<CategoryPojo> sectionAdapter = new SimpleSectionAdapter<CategoryPojo>(
this, adapter, R.layout.section_header, R.id.title,
alphabetSectionizer);
listView.setFastScrollEnabled(true);
listView.setTextFilterEnabled(true);
listView.setAdapter(sectionAdapter);
and this is simplesectionadapter
public class SimpleSectionAdapter<T> extends BaseAdapter implements Filterable{
static final boolean DEBUG = false;
static final String TAG = SimpleSectionAdapter.class.getSimpleName();
// Constants
private static final int VIEW_TYPE_SECTION_HEADER = 0;
// Attributes
private Context mContext;
private BaseAdapter mListAdapter;
private int mSectionHeaderLayoutId;
private int mSectionTitleTextViewId;
private Sectionizer<T> mSectionizer;
private LinkedHashMap<String, Integer> mSections;
AlphabetIndexer alphaIndexer;
private Filter filter;
/**
* Constructs a {#linkplain SimpleSectionAdapter}.
*
* #param context The context for this adapter.
* #param listAdapter A {#link ListAdapter} that has to be sectioned.
* #param sectionHeaderLayoutId Layout Id of the layout that is to be used for the header.
* #param sectionTitleTextViewId Id of a TextView present in the section header layout.
* #param sectionizer Sectionizer for sectioning the {#link ListView}.
*/
public SimpleSectionAdapter(Context context, BaseAdapter listAdapter,
int sectionHeaderLayoutId, int sectionTitleTextViewId,
Sectionizer<T> sectionizer) {
if(context == null) {
throw new IllegalArgumentException("context cannot be null.");
} else if(listAdapter == null) {
throw new IllegalArgumentException("listAdapter cannot be null.");
} else if(sectionizer == null) {
throw new IllegalArgumentException("sectionizer cannot be null.");
} else if(!isTextView(context, sectionHeaderLayoutId, sectionTitleTextViewId)) {
throw new IllegalArgumentException("sectionTitleTextViewId should be a TextView.");
}
this.mContext = context;
this.mListAdapter = listAdapter;
this.mSectionHeaderLayoutId = sectionHeaderLayoutId;
this.mSectionTitleTextViewId = sectionTitleTextViewId;
this.mSectionizer = sectionizer;
this.mSections = new LinkedHashMap<String, Integer>();
// Find sections
findSections();
}
private boolean isTextView(Context context, int layoutId, int textViewId) {
View inflatedView = View.inflate(context, layoutId, null);
View foundView = inflatedView.findViewById(textViewId);
return foundView instanceof TextView;
}
#Override
public int getCount() {
return mListAdapter.getCount() + getSectionCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
SectionHolder sectionHolder = null;
switch (getItemViewType(position)) {
case VIEW_TYPE_SECTION_HEADER:
if(view == null) {
view = View.inflate(mContext, mSectionHeaderLayoutId, null);
sectionHolder = new SectionHolder();
sectionHolder.titleTextView = (TextView) view.findViewById(mSectionTitleTextViewId);
view.setTag(sectionHolder);
} else {
sectionHolder = (SectionHolder) view.getTag();
}
break;
default:
view = mListAdapter.getView(getIndexForPosition(position),
convertView, parent);
break;
}
if(sectionHolder != null) {
String sectionName = sectionTitleForPosition(position);
sectionHolder.titleTextView.setText(sectionName);
}
return view;
}
#Override
public boolean areAllItemsEnabled() {
return mListAdapter.areAllItemsEnabled() ?
mSections.size() == 0 : false;
}
#Override
public int getItemViewType(int position) {
int positionInCustomAdapter = getIndexForPosition(position);
return mSections.values().contains(position) ?
VIEW_TYPE_SECTION_HEADER :
mListAdapter.getItemViewType(positionInCustomAdapter) + 1;
}
#Override
public int getViewTypeCount() {
return mListAdapter.getViewTypeCount() + 1;
}
#Override
public boolean isEnabled(int position) {
return mSections.values().contains(position) ?
false : mListAdapter.isEnabled(getIndexForPosition(position));
}
#Override
public Object getItem(int position) {
return mListAdapter.getItem(getIndexForPosition(position));
}
#Override
public long getItemId(int position) {
return mListAdapter.getItemId(getIndexForPosition(position));
}
#Override
public void notifyDataSetChanged() {
mListAdapter.notifyDataSetChanged();
findSections();
super.notifyDataSetChanged();
}
/**
* Returns the actual index of the object in the data source linked to the this list item.
*
* #param position List item position in the {#link ListView}.
* #return Index of the item in the wrapped list adapter's data source.
*/
public int getIndexForPosition(int position) {
int nSections = 0;
Set<Entry<String, Integer>> entrySet = mSections.entrySet();
for(Entry<String, Integer> entry : entrySet) {
if(entry.getValue() < position) {
nSections++;
}
}
return position - nSections;
}
static class SectionHolder {
public TextView titleTextView;
}
private void findSections() {
int n = mListAdapter.getCount();
int nSections = 0;
mSections.clear();
for(int i=0; i<n; i++) {
String sectionName = mSectionizer.getSectionTitleForItem((T) mListAdapter.getItem(i));
if(!mSections.containsKey(sectionName)) {
mSections.put(sectionName, i + nSections);
nSections ++;
}
}
if(DEBUG) {
Log.d(TAG, String.format("Found %d sections.", mSections.size()));
}
}
private int getSectionCount() {
return mSections.size();
}
private String sectionTitleForPosition(int position) {
String title = null;
Set<Entry<String, Integer>> entrySet = mSections.entrySet();
for(Entry<String, Integer> entry : entrySet) {
if(entry.getValue() == position) {
title = entry.getKey();
break;
}
}
return title;
}
You can use addTextChangedListener & in onTextChanged method get your search string & match this string with your listItems & prepare new list of searched items.Then reinitialize your adapter & set it to ListView.

hide section labels in listview

I use component android-section-list (http://code.google.com/p/android-section-list/) to create sections in my listView. How can I hide sections after push some button?
I try to do like
public void onClick(View v) {
switch(v.getId()) {
case R.id.sortTitle:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.market_list_separator, null, false);
TextView separatorLayout = (TextView) convertView.findViewById(R.id.section_view);
separatorLayout.setVisibility(View.GONE);
sectionAdapter.notifyDataSetChanged();
setButtonState(sortByTitle);
adapter.sort((Comparator<SectionListItem>) sortByTitle());
break;
}
}
But this way don't work.
My adapter put data in list rows and SectionListAdapter draw sections.
public class SectionListAdapter extends BaseAdapter implements ListAdapter,
OnItemClickListener {
private final DataSetObserver dataSetObserver = new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
updateSessionCache();
}
#Override
public void onInvalidated() {
super.onInvalidated();
updateSessionCache();
};
};
private final ListAdapter linkedAdapter;
private final Map<Integer, String> sectionPositions = new LinkedHashMap<Integer, String>();
private final Map<Integer, Integer> itemPositions = new LinkedHashMap<Integer, Integer>();
private final Map<View, String> currentViewSections = new HashMap<View, String>();
private int viewTypeCount;
protected final LayoutInflater inflater;
private View transparentSectionView;
private OnItemClickListener linkedListener;
public SectionListAdapter(final LayoutInflater inflater,
final ListAdapter linkedAdapter) {
this.linkedAdapter = linkedAdapter;
this.inflater = inflater;
linkedAdapter.registerDataSetObserver(dataSetObserver);
updateSessionCache();
}
private boolean isTheSame(final String previousSection,
final String newSection) {
if (previousSection == null) {
return newSection == null;
} else {
return previousSection.equals(newSection);
}
}
private synchronized void updateSessionCache() {
int currentPosition = 0;
sectionPositions.clear();
itemPositions.clear();
viewTypeCount = linkedAdapter.getViewTypeCount() + 1;
String currentSection = null;
final int count = linkedAdapter.getCount();
for (int i = 0; i < count; i++) {
final SectionListItem item = (SectionListItem) linkedAdapter
.getItem(i);
if (!isTheSame(currentSection, item.section)) {
sectionPositions.put(currentPosition, item.section);
currentSection = item.section;
currentPosition++;
}
itemPositions.put(currentPosition, i);
currentPosition++;
}
}
public synchronized int getCount() {
return sectionPositions.size() + itemPositions.size();
}
public synchronized Object getItem(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
final int linkedItemPosition = getLinkedPosition(position);
return linkedAdapter.getItem(linkedItemPosition);
}
}
public synchronized boolean isSection(final int position) {
return sectionPositions.containsKey(position);
}
public synchronized String getSectionName(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
return null;
}
}
public long getItemId(final int position) {
if (isSection(position)) {
return sectionPositions.get(position).hashCode();
} else {
return linkedAdapter.getItemId(getLinkedPosition(position));
}
}
protected Integer getLinkedPosition(final int position) {
return itemPositions.get(position);
}
#Override
public int getItemViewType(final int position) {
if (isSection(position)) {
return viewTypeCount - 1;
}
return linkedAdapter.getItemViewType(getLinkedPosition(position));
}
private View getSectionView(final View convertView, final String section) {
View theView = convertView;
if (theView == null) {
theView = createNewSectionView();
}
setSectionText(section, theView);
replaceSectionViewsInMaps(section, theView);
return theView;
}
protected void setSectionText(final String section, final View sectionView) {
final TextView textView = (TextView) sectionView.findViewById(R.id.listTextView);
textView.setText(section);
}
protected synchronized void replaceSectionViewsInMaps(final String section,
final View theView) {
if (currentViewSections.containsKey(theView)) {
currentViewSections.remove(theView);
}
currentViewSections.put(theView, section);
}
protected View createNewSectionView() {
return inflater.inflate(R.layout.section_view, null);
}
public View getView(final int position, final View convertView,
final ViewGroup parent) {
if (isSection(position)) {
return getSectionView(convertView, sectionPositions.get(position));
}
return linkedAdapter.getView(getLinkedPosition(position), convertView,
parent);
}
#Override
public int getViewTypeCount() {
return viewTypeCount;
}
#Override
public boolean hasStableIds() {
return linkedAdapter.hasStableIds();
}
#Override
public boolean isEmpty() {
return linkedAdapter.isEmpty();
}
#Override
public void registerDataSetObserver(final DataSetObserver observer) {
linkedAdapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
linkedAdapter.unregisterDataSetObserver(observer);
}
#Override
public boolean areAllItemsEnabled() {
return linkedAdapter.areAllItemsEnabled();
}
#Override
public boolean isEnabled(final int position) {
if (isSection(position)) {
return true;
}
return linkedAdapter.isEnabled(getLinkedPosition(position));
}
public void makeSectionInvisibleIfFirstInList(final int firstVisibleItem) {
final String section = getSectionName(firstVisibleItem);
// only make invisible the first section with that name in case there
// are more with the same name
boolean alreadySetFirstSectionIvisible = false;
for (final Entry<View, String> itemView : currentViewSections
.entrySet()) {
if (itemView.getValue().equals(section)
&& !alreadySetFirstSectionIvisible) {
itemView.getKey().setVisibility(View.INVISIBLE);
alreadySetFirstSectionIvisible = true;
} else {
itemView.getKey().setVisibility(View.VISIBLE);
}
}
for (final Entry<Integer, String> entry : sectionPositions.entrySet()) {
if (entry.getKey() > firstVisibleItem + 1) {
break;
}
setSectionText(entry.getValue(), getTransparentSectionView());
}
}
public synchronized View getTransparentSectionView() {
if (transparentSectionView == null) {
transparentSectionView = createNewSectionView();
}
return transparentSectionView;
}
protected void sectionClicked(final String section) {
//
}
public void onItemClick(final AdapterView< ? > parent, final View view,
final int position, final long id) {
if (isSection(position)) {
sectionClicked(getSectionName(position));
} else if (linkedListener != null) {
linkedListener.onItemClick(parent, view,
getLinkedPosition(position), id);
}
}
public void setOnItemClickListener(final OnItemClickListener linkedListener) {
this.linkedListener = linkedListener;
}
}
Where can I put check for visibility in this Adapter?
This works but will be overwritten by the getView() method in the adapter . You must handle this in the adapter bcoz each time view becomes visible on the screen the View is updated so becomes visible in your case.
For the Data you are storing add a Visibility field ( by default keep it visible ) and change the Visibility to GONE in the onClick() method.
if you dont understand , post me your code and will let you know what changes to make.

Categories

Resources