Why NullPointerException is giving on adding a tab? - android

I am making an application in which I am having three tabs and respective fragment to that.But now I want to add one more tab but when I am adding it there is no issue but when i run my app it throws nullpointerexception.I dont why it is happening so.
Please tell me where I m wrong.
This my Activity in which all tab is there:
public class MainActivity extends Activity {
RelativeLayout rl;
PopupWindow popUp;
LinearLayout layout;
TextView tv;
LayoutParams params;
LinearLayout mainLayout;
Button but;
boolean click = true;
ActionBar.Tab TabOrder , TabCart,TabHistory;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getOverflowMenu();
rl = (RelativeLayout) findViewById(R.id.mainLayout);
//fragMentTra = getFragmentManager().beginTransaction();
ActionBar actionbar = getActionBar();
actionbar.setTitle("Select To Order");
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// bar.addTab(bar.newTab().setText("ORDER").setTabListener((TabListener) this));
// bar.addTab(bar.newTab().setText("CART").setTabListener(this));
// bar.addTab(bar.newTab().setText("HISTORY").setTabListener(this));
//TabOrder = actionbar.newTab().setText("DEAL");
TabOrder = actionbar.newTab().setText("ORDER");
TabCart = actionbar.newTab().setText("CART");
TabHistory = actionbar.newTab().setText("HISTORY");
//Fragment FragmentDeal = new FragmentDeal();
Fragment FragmentOrder = new FragmentOrder();
Fragment FragmentCart = new FragmentCart();
Fragment FragmentHistory = new FragmentHistory();
//TabOrder.setTabListener(new MyTablistenerClass(FragmentDeal));
TabOrder.setTabListener(new MyTablistenerClass(FragmentOrder));
TabCart.setTabListener(new MyTablistenerClass(FragmentCart));
TabHistory.setTabListener(new MyTablistenerClass(FragmentHistory));
//actionbar.addTab(TabDeal);
actionbar.addTab(TabOrder);
actionbar.addTab(TabCart);
actionbar.addTab(TabHistory);
}
private void getOverflowMenu() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
FragmentOrder
#SuppressLint({ "ValidFragment", "NewApi" })
public class FragmentOrder extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View view = inflater.inflate(R.layout.g, null);
View view = inflater.inflate(R.layout.gridview,null);
final GridView listView = (GridView) view.findViewById(R.id.mainGrid);
listView.setAdapter(new OrderAdapter());
//listView.setSelection(setselected,true);
listView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
//listView.setLongClickable(false);
int selectCount = listView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount +"items selected");
break;
}
}
});
return view;
}
}
OrderAdapter
private class OrderAdapter extends BaseAdapter {
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//CheckableLayout l;
View myView = convertView;
LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.grid_items_ontap, null);
// Add The Image!!!
ImageView iv = (ImageView)myView.findViewById(R.id.grid_item_image_OnTap);
iv.setImageResource(mThumbIds[position]);
// Add The Text!!!
TextView tv = (TextView)myView.findViewById(R.id.grid_item_text_onTap);
tv.setText(names[position] );
return myView;
}
}
private Integer[] mThumbIds = {
R.drawable.car, R.drawable.car,
R.drawable.car, R.drawable.car,
R.drawable.car,R.drawable.car,R.drawable.car,R.drawable.car, R.drawable.car,
R.drawable.car, R.drawable.car,
R.drawable.car,R.drawable.car,R.drawable.car
};
private String[] names={"ab","cd","ef","gh","ij","kl","mn","","","","","","",""};
FragmentHistory
#SuppressLint("ValidFragment")
public class FragmentHistory extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.activity_fragmenthistory,
(ViewGroup)
findViewById(R.id.layout_root_history));
ListView lv = (ListView) layout.findViewById(R.id.listViewHistory);
lv.setAdapter(new HistoryListViewAdapter(MainActivity.this));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.this);
dlg.setTitle("ORDERID");
dlg.setPositiveButton("REORDER",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton("EDIT AND ORDER", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
ListView listView = new ListView(MainActivity.this);
listView.setAdapter(new DialogListAdapter(MainActivity.this));
dlg.setView(listView);
//((Dialog) dlg).setCanceledOnTouchOutside(true);
// show it
dlg.show();
}
});
return layout;
}
}
FragmentCart
#SuppressLint("ValidFragment")
public class FragmentCart extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.activity_fragmentcart,
(ViewGroup)
findViewById(R.id.layout_root_cart));
ListView lv = (ListView) layout.findViewById(R.id.listViewCart);
lv.setAdapter(new CartListViewAdapter(MainActivity.this));
//lv.invalidateViews();
return layout;
}
}
FragmentDeal
#SuppressLint("ValidFragment")
public class FragmentDeal extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragmentdeal,
(ViewGroup)
findViewById(R.id.layoutdeal));
//View view = inflater.inflate(R.layout.griddeal,null);
final GridView listView = (GridView) layout.findViewById(R.id.GridDeal);
listView.setAdapter(new DealAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
});
return layout;
// TODO Auto-generated method stub
}
}
private class DealAdapter extends BaseAdapter {
#Override
public int getCount() {
return mThumbIds1.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//CheckableLayout l;
View myView = convertView;
LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.griddealitems, null);
// Add The Image!!!
ImageView iv = (ImageView)myView.findViewById(R.id.grid_deal_image);
iv.setImageResource(mThumbIds1[position]);
// Add The Text!!!
TextView tv = (TextView)myView.findViewById(R.id.grid_deal_text);
tv.setText(names1[position] );
return myView;
}
private Integer[] mThumbIds1 = {
R.drawable.car, R.drawable.car,
R.drawable.car, R.drawable.car
};
private String[] names1={"ab","cd","ef","gh"};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_settings:
Intent intentForSettings = new Intent(MainActivity.this, SettingsMenu.class);
startActivity(intentForSettings);
return true;
case R.id.action_info:
Intent intentForInformation = new Intent(MainActivity.this,InformationMenu.class);
startActivity(intentForInformation);
return true;
case R.id.action_ContactUs:
Intent dial = new Intent();
String no = "9579839314";
dial.setAction("android.intent.action.DIAL");
dial.setData(Uri.parse("tel:"+ no));
startActivity(dial);
return true;
}
return false;
}
public class MyTablistenerClass implements android.app.ActionBar.TabListener {
Fragment fragment1;
#SuppressLint("NewApi")
public MyTablistenerClass(Fragment fragment){
this.fragment1 = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
FragmentTransaction fragMentTra;
if (tab.getText().equals("DEAL")) {
try {
rl.removeAllViews();
} catch (Exception e) {
}
FragmentDeal Fram1 = new FragmentDeal();
//fragMentTra.addToBackStack(null);
fragMentTra = getFragmentManager().beginTransaction();
fragMentTra.add(rl.getId(), Fram1);
fragMentTra.commit();
}
else if (tab.getText().equals("ORDER")) {
try {
rl.removeAllViews();
} catch (Exception e) {
}
FragmentOrder Fram2 = new FragmentOrder();
//fragMentTra.addToBackStack(null);
fragMentTra = getFragmentManager().beginTransaction();
fragMentTra.add(rl.getId(), Fram2);
fragMentTra.commit();
}
else if(tab.getText().equals("CART")){
try {
rl.removeAllViews();
} catch (Exception e) {
}
FragmentCart fram3 = new FragmentCart();
//fragMentTra.addToBackStack(null);
fragMentTra = getFragmentManager().beginTransaction();
fragMentTra.add(rl.getId(), fram3);
fragMentTra.commit();
}
else if(tab.getText().equals("HISTORY")){
try {
rl.removeAllViews();
} catch (Exception e) {
}
FragmentHistory fram4 = new FragmentHistory();
//fragMentTra.addToBackStack(null);
fragMentTra = getFragmentManager().beginTransaction();
fragMentTra.add(rl.getId(), fram4);
fragMentTra.commit();
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
}
On adding tabdeal I am facing problem.FragmentDeal is its respective Fragment.If anyone can see where I am wrong tell me.
Thanks.

//TabOrder = actionbar.newTab().setText("DEAL");
TabOrder = actionbar.newTab().setText("ORDER");
You have set both tabs to TabOrder . Set the first as TabDeal.
EDIT:
Of course you also need to initialize the TabDeal here too:
ActionBar.Tab TabOrder , TabCart,TabHistory;
And by the way, usually only class names start with an uppercase letter. This lead to some confusion for me.

Related

Android searchView not searching the list until fully scrolled

I have a listview with a custom adapter, and Im trying to use SearchView with a CustomFilter. But the search is not "fully" working.
When I search for something that is on the viewable area of the listview, it is able to search, and all nonviewable area is not being included in the search.
Here is a video on whats going on:
https://youtu.be/2Z9FZMlNmGw
main
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_board_game_list, container, false);
this.listView = (ListView) view.findViewById(R.id.listView);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this.getContext());
databaseAccess.open();
List<String> boardgamesNames = databaseAccess.getNames();
List<String> urls = databaseAccess.getUrls();
adapter = new bgAdapter(getContext(), R.layout.row_layout);
adapterOriginal = new bgAdapter(getContext(), R.layout.row_layout);
databaseAccess.close();
listView.setAdapter(adapter);
int i = 0;
for(String name: boardgamesNames) {
boardgameListRow data = new boardgameListRow(urls.get(i), boardgamesNames.get(i));
i++;
adapter.add(data);
adapterOriginal.add(data);
}
listView.setDivider(null);
listView.setDividerHeight(0);
searchView = (SearchView)view.findViewById(R.id.searchId);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
adapter.getFilter().filter(newText);
}
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
BoardGameListFragment fragment= new BoardGameListFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
//adapter = adapterOriginal;
return true;
}
});
// Inflate the layout for this fragment
return view;
}
}
Here is the Adapter:
https://github.com/Shank09/AndroidTemp/blob/master/bgAdapter.java
I think you need to call notifyDataSetChanged() in onQueryTextChange
I fixed it, I was using the wrong variable in bgAdapter. Please remove this question if possible.
public class Listbyoperator extends Activity {
ListView lstdetail;
Activity act;
EditText search;
ArrayList<DetailModel> detail=new ArrayList<DetailModel>();
DetailaAdapter dadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listbyoperator);
act=this;
lstdetail=(ListView) findViewById(R.id.Listbyoperator_detaillist);
search=(EditText) findViewById(R.id.editsearch);
search.setPadding(10, 0, 0, 0);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
DetailModel d=new DetailModel("1","HARDIP","saahi");
detail.add(d);
DetailModel d1=new DetailModel("2","jalpa","sadfsadf");
detail.add(d1);
dadapter=new DetailaAdapter(act, detail);
lstdetail.setAdapter(dadapter);
dadapter.notifyDataSetChanged();
lstdetail.setEnabled(true);
}
}
/*Detail Model*/
public class DetailModel
{
public String d_id,d_name,d_decription;
public String getD_id() {
return d_id;
}
public void setD_id(String d_id) {
this.d_id = d_id;
}
public String getD_name() {
return d_name;
}
public void setD_name(String d_name) {
this.d_name = d_name;
}
public String getD_decription() {
return d_decription;
}
public void setD_decription(String d_decription) {
this.d_decription = d_decription;
}
public DetailModel(String s1,String s2,String s3)
{
this.d_id=s1;
this.d_name=s2;
this.d_decription=s3;
}
}
/*detail adapter */
public class DetailaAdapter extends BaseAdapter{
Context mContext;
private List<DetailModel> data=null;
private ArrayList<DetailModel> arraylist;
private static LayoutInflater inflater=null;
private static String String=null,valid;
public boolean flag=true;
public DetailaAdapter(Context context,List<DetailModel> data)
{
mContext = context;
this.data = data;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<DetailModel>();
this.arraylist.addAll(data);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_detail, null);
final TextView t1,t2,t3,t4,t5;
t1=(TextView)vi.findViewById(R.id.list_detail_text1);
t2=(TextView)vi.findViewById(R.id.list_detail_textview2);
t3=(TextView)vi.findViewById(R.id.list_detail_text2);
DetailModel da =new DetailModel(String, String,String);
da=data.get(position);
final String a1,a2,a3;
a1=da.d_id;
a2=da.d_name;
a3=da.d_decription;
t2.setText(a3);//description
t3.setText(a2);//name
return vi;
}
public void filter(String charText)
{
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.addAll(arraylist);
}
else
{
for (DetailModel wp : arraylist)
{
if (wp.getD_decription().toLowerCase(Locale.getDefault()).contains(charText) || wp.getD_name().toLowerCase(Locale.getDefault()).contains(charText))
{
data.add(wp);
}
}
}
notifyDataSetChanged();
}
}

How to pass a row in listview in a fragment to listview in another fragment in same activity when click button in row?

I have two fragments in one activity and there is a ViewPager element in main_activity.xml. I have created two different classes that exteds Fragment class for each fragments and overrided onCreateView methods. The first fragment is a channels list. So it's a listview that its each row consist of a textview and a button. I want when the user click the button, get passed the row to listView in second fragment. I created a interface in ChannelsFragment named FavButtonClickedListener and overrided this interface in MainActivity.java. Then I added onAttach() method into ChannelsFragment in order to reference MainActivity. In getView method of Adapter of ChannelsFragment class I have set the clicklistener to imageButtons in each row and I called whenFavButtonClicked.onFavButtonClicked(); My code is working for SharedPreferences hovewer I need to restart the application to see changes in favorites list. I want to add the rows dynamically. I don't know where I wrong please help me
ChannelsFragment :
public class ChannelsFragment extends Fragment {
ViewGroup rootVg;
Context context;
FavButtonClickedListener whenFavButtonClicked;
private final List<String> favValues = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.channels_list_layout, container, false);
final ListView channelsList = (ListView) rootView.findViewById(R.id.channelsListView);
String[] chNames = new String[]{"ChA","ChB","ChC"};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < chNames.length; ++i) {
list.add(chNames[i]);
}
//set adapter to listview
MyListAdapter listAdapter = new MyListAdapter(getActivity(),chNames);
channelsList.setAdapter(listAdapter);
return rootView;
}
public interface FavButtonClickedListener {
public void onFavButtonClicked(int position,List<String>favs);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = getActivity();
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
whenFavButtonClicked = (FavButtonClickedListener)context;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
}
ChannelsFragment Adapter class:
public class MyListAdapter extends ArrayAdapter<String>{
private final Context context;
private final String[] values;
URL channelUrl;
public MyListAdapter(Context context, String[] values) {
super(context, R.layout.list_item_complex, values);
this.context = context;
this.values = values;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public long getCount(int position) {
// TODO Auto-generated method stub
return values.length;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_item_complex, parent, false);
TextView chNameText = (TextView) rowView.findViewById(R.id.chName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.chImage);
final ImageButton imageButton = (ImageButton)rowView.findViewById(R.id.starButon);
Button chButton = (Button)rowView.findViewById(R.id.chButon);
chNameText.setText(values[position]);
//Set the channels' logo appropriately
if(values[position].equals("CHa")){
imageView.setImageResource(R.drawable.CHaImage);
imageButton.setId(0);
}else if(values[position].equals("CHb")){
imageView.setImageResource(R.drawable.CHbImage);
imageButton.setId(1);
}else if(values[position].equals("Chc")){
imageView.setImageResource(R.drawable.CHcImage);
imageButton.setId(2);
}else{
imageView.setImageResource(R.drawable.defult_bacground_logo);
}
}
//Determine the target url for each channel correctly
chButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.intent.action.Activity2");
String chName = null;
if(values[position].equals("CHa")){
i.putExtra("CHa", "http://www.cha.com/");
chName = "CHa";
i.putExtra("nameofCh", ChName);
startActivity(i);
}
if(values[position].equals("CHb")){
i.putExtra("CHb", "http://www.chb.com/");
chName = "CHb";
i.putExtra("nameofCh",ChName);
startActivity(i);
}
if(values[position].equals("CHc")){
i.putExtra("CHc", "http://www.chc.com/");
chName = "CHc";
i.putExtra("nameofCh",ChName);
startActivity(i);
}
});
final Context konteks;
konteks = this.getContext();
//set button click for favorite channels list
// I use this imageButton for create a favorites list in listview in FavoritesChannels
//fragment. I want when the user click this button, the row that has been clicked, get
//passed to FavoritesChannels fragment
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageButton.setImageResource(R.drawable.button_states_star);
SharedPreferences prefs = konteks.getSharedPreferences("favorites",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if(imageButton.getId()==0){
editor.putBoolean("CHaChecked", true);
editor.commit();
favValues.add("CHa");
whenFavButtonClicked.onFavButtonClicked(position,favValues);
Toast.makeText(getActivity(), "CHa have been added to favlist", Toast.LENGTH_SHORT).show();
}
else if(imageButton.getId()==1){
editor.putBoolean("CHbChecked", true);
favValues.add("CHb");
editor.commit();
whenFavButtonClicked.onFavButtonClicked(position,favValues);
Toast.makeText(getActivity(), "CHb have been added to favlist", Toast.LENGTH_SHORT).show();
}
else if(imageButton.getId()==2){
editor.putBoolean("CHcChecked", true);
favValues.add("CHc");
editor.commit();
whenFavButtonClicked.onFavButtonClicked(position,favValues);
Toast.makeText(getActivity(), "CHc have been added to favlist", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "CH have been added to favlist", Toast.LENGTH_SHORT).show();
}
}
});
return rowView;
}
}
MainActivity.java:
onFavButtonClicked() implementation is at end of file
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener,KanallarFragment.FavButtonClickedListener {
private static final int NUM_PAGES = 2;
public SharedPreferences prefs;
FragmentTransaction fragmentTransaction;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
//Initiate Actionbar instance and define its tab names
private ActionBar actionBar;
private String[] tabs = { "Channels", "Favorites"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragMgr = getSupportFragmentManager();
fragmentTransaction = fragMgr.beginTransaction();
fragmentTransaction.add(new FavoriteFragment(), "favsFragment");
fragmentTransaction.add(new ChannelsFragment(), "channelsFragment");
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
//ViewPager's PageChangeListener
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
//Retrieve actionbar and set some properties
actionBar = getSupportActionBar();
//actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setStackedBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_gradient));
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
// Adding Tabs to actionbar
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
for(int i = 0; i<actionBar.getTabCount(); i++){
LayoutInflater inflater = LayoutInflater.from(this);
View customView = inflater.inflate(R.layout.tab_layout, null);
TextView titleTV = (TextView) customView.findViewById(R.id.action_custom_title);
titleTV.setText(tabs[i]);
ImageView tabImage = (ImageView)customView.findViewById(R.id.tab_icon);
if(i==0){
tabImage.setImageResource(R.drawable.television_icon_64);
}else{
tabImage.setImageResource(R.drawable.star_icon);
}
actionBar.getTabAt(i).setCustomView(customView);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/*public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
mPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}*/
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new ChannelsFragment();
case 1:
return new FavoritesFragment();
}
return null;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
#Override
public void onTabReselected(Tab arg0,FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0,FragmentTransaction arg1) {
// TODO Auto-generated method stub
mPager.setCurrentItem(arg0.getPosition());
}
#Override
public void onTabUnselected(Tab arg0,FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
public void onFavButtonClicked(int position,List<String>favs) {
// TODO Auto-generated method stub
FavoritesFragment favFrag = (FavoritesFragment)getSupportFragmentManager().findFragmentByTag("favsFragment");
if(favFrag !=null){
favFrag.updateList(position,favs);
}
}
And FavoritesFragment class that contain updateList() method :
public class FavorilerFragment extends Fragment {
Context context;
private final List<String> values = new ArrayList<String>();
private final List<String> favValues = new ArrayList<String>();
ListView listView;
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Context context = getActivity();
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.favorites_list_layout, container, false);
listView = (ListView)rootView.findViewById(R.id.f_channels_ListView);
textView = (TextView)rootView.findViewById(R.id.favListMessage);
SharedPreferences prefs = context.getSharedPreferences("favorites",getActivity().MODE_PRIVATE);
//-----SharedPreferences values for adapter----
if(prefs.getBoolean("CHaChecked", false)){
values.add("Cha");
}
if(prefs.getBoolean("CHbChecked", false)){
values.add("Chb");
}
if(prefs.getBoolean("ChcChecked", false)){
values.add("Chc");
}
//-----------------------------------------------
if(values.size() == 0){
textView.setText("Favorites List is empty");
}else{
textView.setText("");
}
MyListAdapter adapter = new MyListAdapter(getActivity(),values);
listView.setAdapter(adapter);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = getActivity();
}
public void updateList(int position,List<String> argfavValues){
for(int a= 0;a<argFavValues.size();a++){
favValues.add(argFavValues.get(a));
}
MyListAdapter = new MyListAdapter(getActivity(),favValues);
adaptor.notifyDataSetChanged();
listView.setAdapter(adapter);
}
public static class MyListAdapter extends ArrayAdapter<String>{
private final Context context;
private final List<String> values = new ArrayList<String>();
URL ChUrl;
public MyListAdapter(Context context, List<String> values) {
super(context, R.layout.list_item_complex_fav, values);
this.context = context;
for(int i=0;i<values.size();i++){
this.values.add(values.get(i));
}
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public long getCount(int position) {
// TODO Auto-generated method stub
return values.size();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_item_complex_fav, parent, false);
TextView chNameText = (TextView) rowView.findViewById(R.id.ChName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ChannelsImage);
Button chButton = (Button)rowView.findViewById(R.id.chButon);
chNameText.setText(values.get(position));
//Set the channels' logo appropriately
if(values.get(position).equals("CHa")){
imageView.setImageResource(R.drawable.CHaImage);
}else if(values.get(position).equals("CHb")){
imageView.setImageResource(R.drawable.CHbImage);
}else if(values.get(position).equals("CHc")){
imageView.setImageResource(R.drawable.CHcImage);
else{
imageView.setImageResource(R.drawable.default_logo);
}
return rowView;
}
}
Per the official documentation, fragment to fragment communication should be routed through the activity.
You need to create an interface in your channels fragment with some callback method defined, like onSelected. When a list item is selected, call that interface method using the activity context:
public class ChannelsFragment extends ListFragment {
OnItemSelectedListener mCallback;
public interface OnItemSelectedListener {
public void onSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnItemSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
mCallback.onSelected(position);
}
}
Then, your activity needs to implement ChannelFragment.OnItemSelectedListener and define the callback method.
public void onSelected(int position) {
Fragment2 fragment = (Fragment2)
getSupportFragmentManager().findFragmentById(R.id.fragment2);
if (fragment != null) {
fragment.updateValue(position);
}
}
You can pass data via parameters. To send the data to the other fragment, create a public method in the fragment which can be called directly from the activity.

How to add dymnamically selected gridview items in listview

First activity : gridview, whenever u click on gridview item dialogBox is opened which contains spinner. Now, I want to display Selected Gridview item and selected spinner values in Second Activity contains Listview. When u click on secondtime the values are replaced in listview but not added.
Can anyone plz help me...........
MainActivity...
public class MainActivity extends Activity implements OnClickListener {
SharedPreferences SharedPrefs;
String sp_selected;
Spinner sp;
String s1;
String partname;
String partname1;
Button Parts_history;
Imageadapter image_adapter;
private static final String[] paths = { "Select Your Choice", "Type1",
"Type2", "Type3", "Type4" };
private static final int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.partsrepair);
image_adapter = new Imageadapter(this);
SharedPrefs = getSharedPreferences("Preference", MODE_PRIVATE);
GridView gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(new Imageadapter(this));
Parts_history = (Button) findViewById(R.id.partshistory_button);
Parts_history.setOnClickListener((this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, View v,
int position, long id) {
SharedPreferences.Editor edit = SharedPrefs.edit();
// partname = parent.getItemAtPosition(position).toString();
partname1 = image_adapter.names[position].toString();
image_adapter.names[position].toString();
Toast.makeText(MainActivity.this, "you Selected:" + partname1,
Toast.LENGTH_SHORT).show();
// edit.putString("SelectPart", partname1);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.repairtype_spinner);
dialog.setCancelable(true);
Spinner sp = (Spinner) dialog.findViewById(R.id.spinner_1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_spinner_item,paths);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
if (position > 0) {
sp_selected = parent.getItemAtPosition(position)
.toString();
}
}
#Override
public void onNothingSelected(AdapterView<?>arg0) {
// TODO Auto-generated method stub
}
});
Button btnOk = (Button)dialog.findViewById(R.id.Button_sms_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor edit = SharedPrefs.edit();
if ((sp_selected != null)
&& !sp_selected.equals("Select Your Choice")) { //
edit.putString("SelectType", sp_selected);
Toast.makeText(getApplicationContext(),
"You selected:" + sp_selected,
Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"Thank You!", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {
Toast.makeText(MainActivity.this,
"plz Select your Choice",
Toast.LENGTH_SHORT).show();
}} });
dialog.show(); }});}
public void onClick(View v) {
switch (v.getId()) {
case R.id.partshistory_button:
Intent intent = new Intent(MainActivity.this, ListViewItems.class);
intent.putExtra("Part", partname1);
intent.putExtra("Type", sp_selected);
startActivity(intent);
finish();
}}}
listview.class
public class ListViewItems extends Activity {
ArrayList<String> part, type;
ListView list;
public ListViewItems() {
// TODO Auto-generated constructor stub
part = new ArrayList<String>();
type = new ArrayList<String>();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_summary);
Intent i = getIntent();
part.add(i.getStringExtra("Part"));
type.add(i.getStringExtra("Type"));
list = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(), R.layout.listview, type);
list.setAdapter(new CustomViewAdapter(ListViewItems.this));
adapter.notifyDataSetChanged();
}
public class CustomViewAdapter extends BaseAdapter {
Context context;
public CustomViewAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
private class ViewHolder {
TextView text_part;
TextView text_type;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
// Log.d("hao",""+position);
LayoutInflater minflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = minflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.text_part = (TextView) convertView
.findViewById(R.id.textView1);
// Log.d("hao", ""+holder.text_desc);
holder.text_type = (TextView) convertView
.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.text_type.setText(type.get(position));
holder.text_part.setText(part.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return part.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}}
Imageadapter.class
public class Imageadapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mlayoutinflater;
public Imageadapter(Context c) {
mContext = c;
mlayoutinflater = LayoutInflater.from(c);
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
class ViewHolder {
ImageView imageView;
TextView textView;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
ViewHolder childHolder;
if (convertView == null) {
// if it's not recycled, initialize some
convertView = mlayoutinflater.inflate(R.layout.partsnames, null);
childHolder = new ViewHolder();
childHolder.imageView = (ImageView) convertView
.findViewById(R.id.imageView1);
childHolder.textView = (TextView) convertView
.findViewById(R.id.textView1);
convertView.setTag(childHolder);
} else {
childHolder = (ViewHolder) convertView.getTag();
}
childHolder.imageView.setImageResource(mThumbIds[position]);
childHolder.textView.setText(names[position]);
return convertView;
}
public Integer[] mThumbIds = { R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher, };
public String[] names = { "First", "Second", "Third", "Fourth",
"Fifth", "Sixth", "Seventh" };
}
It seems the values are not really being overwritten. Each time the second activity is loaded new part and type ArrayLists are being created. In these new lists only the latest part and type are added (in the onCreate Function) which have travelled with the intent.
If you want the list to keep adding the part and type selected by the user you can maintain the lists on the MainActivity. So upon selection of each item and type add it to the list on the MainActivity and then pass it to the ListViewItems activity.
This way the list will always have all the items selected by you.
I must admit I am not 100% sure if I understood your question correctly. But I have tried to answer with as much as I did.
EDIT:
MainActivity:
public class MainActivity extends ActionBarActivity {
ArrayList<String> list;
int clickCount = 0;
static TextView textViewHelloWorld;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
list = new ArrayList<String>();
textViewHelloWorld = (TextView) findViewById(R.id.textViewHelloWorld);
Button buttonAddElements = (Button) findViewById(R.id.buttonAddElement);
buttonAddElements.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
clickCount = clickCount + 1;
textViewHelloWorld.setText("Click Count" + clickCount);
list.add("Click number " + clickCount);
}
});
Button buttonStartNewActivity = (Button) findViewById (R.id.buttonStartNewActivity);
buttonStartNewActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle bundle = new Bundle();
bundle.putStringArrayList("list", list);
startActivity(new Intent(MainActivity.this, Main2Activity.class).putExtras(bundle));
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Main2Activity: (ListView Activity):
public class Main2Activity extends ActionBarActivity {
ArrayList<String> list;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
list = getIntent().getStringArrayListExtra("list");
listView = (ListView) findViewById(R.id.listViewList);
String []dsf = new String[list.size()];
list.toArray(dsf);
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, dsf));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main2,
container, false);
return rootView;
}
}
}
EDIT2:
MainActivity.Java
public class MainActivity extends Activity implements OnClickListener {
SharedPreferences SharedPrefs;
String sp_selected;
Spinner sp;
String s1;
String partname;
String partname1;
Button Parts_history;
private ArrayList<String> parts;
private ArrayList<String> types;
Imageadapter image_adapter;
private static final String[] paths = { "Select Your Choice", "Type1",
"Type2", "Type3", "Type4" };
private static final int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.partsrepair);
image_adapter = new Imageadapter(this);
parts = new ArrayList<String>();
types = new ArrayList<String>();
SharedPrefs = getSharedPreferences("Preference", MODE_PRIVATE);
GridView gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(new Imageadapter(this));
Parts_history = (Button) findViewById(R.id.partshistory_button);
Parts_history.setOnClickListener((this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, View v,
int position, long id) {
SharedPreferences.Editor edit = SharedPrefs.edit();
// partname = parent.getItemAtPosition(position).toString();
partname1 = image_adapter.names[position].toString();
parts.add(partname1);
image_adapter.names[position].toString();
Toast.makeText(MainActivity.this, "you Selected:" + partname1,
Toast.LENGTH_SHORT).show();
// edit.putString("SelectPart", partname1);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.repairtype_spinner);
dialog.setCancelable(true);
Spinner sp = (Spinner) dialog.findViewById(R.id.spinner_1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_spinner_item,paths);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
if (position > 0) {
sp_selected = parent.getItemAtPosition(position)
.toString();
types.add(sp_selected);
}
}
#Override
public void onNothingSelected(AdapterView<?>arg0) {
// TODO Auto-generated method stub
}
});
Button btnOk = (Button)dialog.findViewById(R.id.Button_sms_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor edit = SharedPrefs.edit();
if ((sp_selected != null)
&& !sp_selected.equals("Select Your Choice")) { //
edit.putString("SelectType", sp_selected);
Toast.makeText(getApplicationContext(),
"You selected:" + sp_selected,
Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"Thank You!", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {
Toast.makeText(MainActivity.this,
"plz Select your Choice",
Toast.LENGTH_SHORT).show();
}} });
dialog.show(); }});}
public void onClick(View v) {
switch (v.getId()) {
case R.id.partshistory_button:
Bundle bundle = new Bundle();
bundle.putStringArrayList("parts", parts);
bundle.putStringArrayList("type", types);
Intent intent = new Intent(MainActivity.this, ListViewItems.class);
intent.putExtra("Part", partname1);
intent.putExtra("Type", sp_selected);
intent.putExtra("bundle", bundle);
startActivity(intent);
finish();
}}}
ListView:
public class ListViewItems extends Activity {
ArrayList<String> part, type;
ListView list;
public ListViewItems() {
// TODO Auto-generated constructor stub
part = new ArrayList<String>();
type = new ArrayList<String>();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_summary);
Intent i = getIntent();
// part.add(i.getStringExtra("Part"));
// type.add(i.getStringExtra("Type"));
part = i.getExtras().getBundle("bundle").getStringArrayList("parts");
type = i.getExtras().getBundle("bundle").getStringArrayList("types");
list = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(), R.layout.listview, type);
list.setAdapter(new CustomViewAdapter(ListViewItems.this));
adapter.notifyDataSetChanged();
}
public class CustomViewAdapter extends BaseAdapter {
Context context;
public CustomViewAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
private class ViewHolder {
TextView text_part;
TextView text_type;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
// Log.d("hao",""+position);
LayoutInflater minflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = minflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.text_part = (TextView) convertView
.findViewById(R.id.textView1);
// Log.d("hao", ""+holder.text_desc);
holder.text_type = (TextView) convertView
.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.text_type.setText(type.get(position));
holder.text_part.setText(part.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return part.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}}

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 implement search functionality?

I am having a grid view and I have to add search functionality in the action bar.So that whatever i type to search,the items should come whatever i searched.Grid view is having image and text.I stuck in this very badly.I dont know how to implement it.I gone through android guide but I unable to get it.
Please suggest some easy way to do it.I need search like in watsaap application.
Any suggestion is appreciated.Thanks.
Here is my gridview code.
public class FragmentDeals extends Fragment implements Checkable{
private boolean mChecked;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragmentdeal,
(ViewGroup)
findViewById(R.id.layoutdeal));
//View view = inflater.inflate(R.layout.griddeal,null);
final GridView mGrid = (GridView) layout.findViewById(R.id.GridDeal);
mGrid.setAdapter(new DealAdapter());
mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
//listView.setLongClickable(false);
int selectCount = mGrid.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount +"items selected");
break;
}
}
});
return layout;
// TODO Auto-generated method stub
}
#Override
public boolean isChecked() {
// TODO Auto-generated method stub
return mChecked;
}
#SuppressWarnings("deprecation")
#Override
public void setChecked(boolean checked) {
// TODO Auto-generated method stub
mChecked = checked;
layout.setBackgroundDrawable(checked ? getResources().getDrawable(
R.drawable.bground) : null);
}
#Override
public void toggle() {
// TODO Auto-generated method stub
setChecked(!mChecked);
}
}
private class DealAdapter extends BaseAdapter {
#Override
public int getCount() {
return mThumbIds1.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//CheckableLayout l;
View myView = convertView;
LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.griddealitems, null);
// Add The Image!!!
ImageView iv = (ImageView)myView.findViewById(R.id.grid_deal_image);
iv.setImageResource(mThumbIds1[position]);
// Add The Text!!!
TextView tv = (TextView)myView.findViewById(R.id.grid_deal_text);
tv.setText(names1[position] );
return myView;
}
private Integer[] mThumbIds1= {
R.drawable.car, R.drawable.car,
R.drawable.car, R.drawable.car,
R.drawable.car,R.drawable.car,R.drawable.car,R.drawable.car, R.drawable.car,
R.drawable.car, R.drawable.car,
R.drawable.car,R.drawable.car,R.drawable.car
};
private String[] names1={"ab","cd","ef","gh","ij","kl","mn","","","","","","",""};
}
I have never tried for search functionality with gridview. But i have done the same for list view. Please have a look on the following link to implement search functionality for listview
Search functionality with list view
http://www.androidbegin.com/tutorial/android-search-listview-using-filter/

Categories

Resources