Fragment Activity and List Adapter Null Pointer Exception Error - android-activity

I created listview and fragment activity.But List Adapter not working.
Fragment Code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_friends, container, false);
Intent intent = new Intent(getActivity(), MainFeed.class);
getActivity().startActivity(intent);
// Inflate the layout for this fragment
return rootView;
}
Activity Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
List Adapter Code:
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
List Adapter is null.
Please help me.

Try changing FeedListAdapter(Activity activity, List feedItems) for FeedListAdapter(Context cntx, List feedItems) i think you are sending the Context and trying to get the Activity in the constructor...

Related

Android nested fragment rendering to main activity

How to render the nested fragment to main activity??
This is my hierarchy mainAcivity has three dynamic fragment
Inside RsOneFragment contain another childone fragment so on...
Main Activity -> RsOneFragment -> ChildOneFragment -> ChildFirstFragment
mainActivity -> RsTwoFragment
mainActivity -> RsThreeFragment
How to render childFistFragemt to mainActivity
how to achieve this, please help
Here is my code snippet
MainAcivity
fragmentOneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter_anim, R.anim.exit_anim);
transaction.replace(R.id.fragmentContainer, new RsOneFragment());
transaction.commit();
}
});
RsOneFragment extends Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rsslist_overview, container, false);
insertNestedFragment();
return view;
}
private void insertNestedFragment() {
Fragment fragment = new ChildOneFragment();
FragmentTransaction transaction =getChildFragmentManager().beginTransaction();
transaction.replace(R.id.child_fragment_container_two, fragment).commit();
}
ChildOneFragment extends Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
childRsOneImage = (ImageView) view.findViewById(R.id.childRsOneImage);
fragmentContainer = (FrameLayout) getActivity().findViewById(R.id.fragmentContainer);
childRsOneImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter_anim, R.anim.exit_anim);
transaction.replace(R.id.fragmentContainer, new ChildFirstFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
childRsOneImage clicking its showing the following error..
Process: com.example.NestedFragmentsExample, PID: 1885
java.lang.IllegalArgumentException: No view found for id 0x7f080055
Hope u would understand my problem...
Any help appreciated..Thanks a lot!!!
I was able to solve the problem myself.
instead of
FragmentManager manager = getFragmentManager();
i replace like this
FragmentManager manager = getActivity().getFragmentManager();
and its working fine...

Android action bar search not working

I want to use my getfilter() i implemented but from action bar in order to search my listview . But dont know why the app keeps on giving nullpointer i cant understand the error as well .
Here's my code calling my custom getfilter implented inside my coustom adapter.
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
ListView itcItems;
DataBaseHandler db;
private SearchView mSearchView;
//private EditText mStatusView;
public DummySectionFragment() {
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
//getMenuInflater().inflate(R.menu.action, menu);
searchView = (SearchView) menu.findItem(R.id.Search).getActionView();
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(newText);
return true;
}
#Override
public boolean onQueryTextSubmit(String query)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(query);
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.common_listview,
container, false);
setHasOptionsMenu(true);
ActionBar actionbar = getActivity().getActionBar();
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
actionbar.show();
//getActivity().requestWindowFeature(Window.FEATURE_ACTION_BAR);
//mStatusView = (EditText) rootView.findViewById(R.id.status_text);
itcItems = (ListView) rootView.findViewById(R.id.streamList);
/*MyAsyncTask task = new MyAsyncTask(getActivity());
task.execute("http://findaway.in/card/restlist.xml");
*
*/
db = new DataBaseHandler(getActivity());
if(isOnline(getActivity()))
{
flag=1;
db.delete();
getDataInAsyncTask();
getImage(db);
//db.close();
}
else
{
flag=0;
Toast.makeText(getActivity(), "No internet",
Toast.LENGTH_LONG).show();
try {
db.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
getDataInDataBase(db);
}
here's my logcat
line 212 is searchView = (SearchView) menu.findItem(R.id.Search).getActionView();
also is it compulsory to implement res/xml/searchable.xml ?? i havnt done that
In onCreateOptionsMenu(), call to super is missing. Consider using super and then using inflater and menu objects.

Unable to load tab in PagerSlidingTabStrip when fragment is replaced

I'm trying to implement a viewpager with a PagerSlidingTabStrip instead of a TabView. The viewpager has three tabs in which each listview displays a list of events. The three tabs are called Past, Tonight and Future.
I've set up the slider as the github page suggests:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.all_events_main_strip, container, false);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
pager = (ViewPager) v .findViewById(R.id.pager_main);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
adapter = new MyPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
// Set Present tab as default
pager.setCurrentItem(1);
return v;
}
When the app starts the Main Activity adds for the first time this fragment and everything works great. 3 swipeable tabs with 3 listviews. (c.f. code section)
Here is the problem:
I've noticed that when I press the back button and replace the fragment again, in order to reopen the viewpager, the tab in the middle doesn't show any listview. If I swype left or right the content in the other tabs is loaded and displayed but the Present Tab remains empty.
When I debug the ToNightEvents ListFragment isn't called at all.
Do you guys have any suggestions to solve the problem?
The code:
The code is structured as follows: After the onCreateView I've added an OnDestroyView method to remove the fragment but it didn't work... Then in the fragmentPagerAdapter each page is called as a fragment in the getItem method. Finally at the end of the code you can see the three ListFragment classes in which a listview is populated through an AsyncTask
public class FragmentAllEvents extends Fragment
{
private static final String TAG_UID = "uid";
private static final String TAG_LOGO = "logo";
private static final String TAG_POKUID = "pokuid";
static ArrayList<HashMap<String, String>> userList;
ArrayList<HashMap<String, String>> userListTotal;
private final Handler handler = new Handler();
HashMap<String, String> userSelected;
EventsFunctions eventsFunctions;
UserFunctions userFunctions;
static ListView lv;
ActionBar actionBar;
MyPagerAdapter adapter;
ViewPager pager;
PagerSlidingTabStrip tabs;
private Drawable oldBackground = null;
private int currentColor = 0xFF666666;
//Context context = this;
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set up the action bar.
actionBar = getActivity().getActionBar();
actionBar.setHomeButtonEnabled(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.all_events_main_strip, container, false);
pager = (ViewPager) v .findViewById(R.id.pager_main);
tabs = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
adapter = new MyPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
pager.setCurrentItem(1);
return v;
}
#Override
public void onDestroyView()
{
super.onDestroyView();
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i)
{
switch (i)
{
case 0:
return new PastEvents();
case 1:
return new ToNightEvents();
case 2:
return new FutureEvents();
/*default:
// The other sections of the app are dummy placeholders.
return new ToNightEvents();
*/
}
return null;
}
/**
* A fragment that launches past events list.
*/
public static class PastEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView pastList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View pastView = inflater.inflate(R.layout.pastlist, container, false);
progress = (ProgressBar) pastView.findViewById(R.id.loading_spinner_past);
tabTime="past";
pastList = (ListView) pastView.findViewById(android.R.id.list);
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(pastList, this);
new AsyncLoadEvents(getActivity(), progress, pastList, mPullToRefreshAttacher).execute(tabTime);
return pastView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
//Log.e("AttendList Report", "Clicked list item: " + position +" Content: \n" + map.get(TAG_ID).toString());
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, pastList, mPullToRefreshAttacher).execute(tabTime);
}
}
/**
* A fragment that launches future event list.
*/
public static class FutureEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView futureList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View futureView = inflater.inflate(R.layout.futurelist, container, false);
progress = (ProgressBar) futureView.findViewById(R.id.loading_spinner_future);
tabTime = "future";
futureList = (ListView) futureView.findViewById(android.R.id.list); //change to attendlist if needed
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(futureList, this);
new AsyncLoadEvents(getActivity(), progress, futureList, mPullToRefreshAttacher).execute(tabTime);
return futureView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, futureList, mPullToRefreshAttacher).execute(tabTime);
}
}
/**
* A fragment that launches future event list.
*/
public static class ToNightEvents extends ListFragment implements
PullToRefreshAttacher.OnRefreshListener
{
private ListView tonightList;
private PullToRefreshAttacher mPullToRefreshAttacher;
ProgressBar progress;
String tabTime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View tonightView = inflater.inflate(R.layout.tonightlist, container, false);
progress = (ProgressBar) tonightView.findViewById(R.id.loading_spinner_tonight);
tabTime = "tonight";
tonightList = (ListView) tonightView.findViewById(android.R.id.list); //change to attendlist if needed
// Now get the PullToRefresh attacher from the Activity. An exercise to the reader
// is to create an implicit interface instead of casting to the concrete Activity
mPullToRefreshAttacher = ((Home) getActivity()).getPullToRefreshAttacher();
// Now set the ScrollView as the refreshable view, and the refresh listener (this)
mPullToRefreshAttacher.addRefreshableView(tonightList, this);
new AsyncLoadEvents(getActivity(), progress, tonightList, mPullToRefreshAttacher).execute(tabTime);
return tonightView;
}
#SuppressWarnings("unchecked")
#Override
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick (listView, view, position, id);
HashMap<String, String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
Log.e("PastList Report", "Clicked list item: " + position +" Event's content: \n" + map.get(TAG_UID).toString());
Intent intent = new Intent(getActivity(), SingleEventActivity.class);
intent.putExtra("pokuid",map.get(TAG_POKUID)); // Maybe remove attribute toString();
intent.putExtra("uid", map.get(TAG_UID));
intent.putExtra("logo",map.get(TAG_LOGO));
getActivity().startActivity(intent);
}
#Override
public void onRefreshStarted(View view)
{
new AsyncLoadEvents(getActivity(), progress, tonightList, mPullToRefreshAttacher).execute(tabTime);
}
}
public String[] titles=
{
"Past",
"Tonight",
"Future"
};
#Override
public int getCount()
{
return titles.length;
}
#Override
public CharSequence getPageTitle(int position)
{
return titles[position];
}
}
}
This would normally work if you were in an Activity, however I guess you are in a Fragment since the code you posted is the method onCreateView(). The problem is that you are trying to use the FragmentManager of the Activity and you should be using the Fragment's FragmentManager. This FragmentManager is not what you need. Try this instead:
adapter = new MyPagerAdapter(getChildFragmentManager());
I think I'm a little bit late but if anyone happens to have the same error here is the solution =)
Q.
The following fixed it for me:
Add an OnBackStackChangedListener to the fragment manager.
In the onBackStackChanged method, get references to both the ViewPager and the PagerSlidingTabStrip (pager and tabs in your example). If the appropriate fragment is currently active, do the following:
pager.invalidate();
tabs.invalidate();
pager.setAdapter(new MyPagerAdapter(getFragmentManager()));
tabs.setViewPager(pager);

Filtering listview data of simple_list_item_2 items using searchview and arrayadapter

I'm writing an android application (Min API 14) which consists of 3 tabs that hold a fragment each.
One of the fragments holds a list view (with a list view item defined as simple_list_item_2) and a search view. Now, I'm trying to filter the data in the list view by a room's name (Room is my model)
protected SearchView searchView;
protected ListView view;
protected List<Room> rooms;
protected ArrayAdapter<Room> roomAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(getLayoutId(), container, false);
view = (ListView)rootView.findViewById(getListViewId());
searchView = (SearchView)rootView.findViewById(R.id.rooms_search_view);
view.setTextFilterEnabled(true);
....
roomAdapter = new ArrayAdapter<Room>(this.getActivity(), android.R.layout.simple_list_item_2, rooms){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if(convertView == null){
LayoutInflater inflater =
(LayoutInflater)getActivity().getApplicationContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (View)inflater.inflate(android.R.layout.simple_list_item_2, null);
}else{
row = (View)convertView;
}
Room data = rooms.get(position);
TextView v = (TextView) row.findViewById(android.R.id.text1);
v.setText(data.getName());
v = (TextView) row.findViewById(android.R.id.text2);
v.setText(data.getPhone());
return row;
}
};
view.setAdapter(roomAdapter);
....
return rootView;
}
#Override
public boolean onQueryTextChange(String newText) {
roomAdapter.getFilter().filter(newText);
return true;
}
The problem is that the search results are in no way relevant to the input entered in the search view. When I replace *android.R.layout.simple_list_item_2* with *android.R.layout.simple_list_item* everything work as expected.
I also read that overriding the toString() method in my model(Room) would solve such a problem,
but that didn't work either.
Any help figuring out how to filter by title(android.R.id.text1) would be highly appreciated.
Well, After I couldn't find any solution with the 'standard' android adapters, I ended up writing a custom adapter that extends BaseAdapter and implements Filterable.
You can find some hints in here if you encounter the same problem.

SimpleCursorAdapter() Depracated, how can I replace it?

I am trying to display data from SQLite to a listview. I try to use the constructor SimpCursorAdapter() but it says it's deprecated and i can't use it. Anyone any idea on how to do this without in any other way??? Below is my code:
public class JournalsTab extends Fragment {
private SimpleCursorAdapter dataAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout l2 = (LinearLayout) inflater.inflate(R.layout.journal, container, false);
BalanceApp myapp= (BalanceApp) getActivity().getApplicationContext();
DataSource datasource = myapp.datasource;
datasource.open();
Cursor cursor = datasource.fetchAllEntries();
int[] to = {R.id.textView1, R.id.textView2, R.id.textView3, R.id.text4};
dataAdapter = new SimpleCursorAdapter(this, R.layout.journal,cursor, datasource.columns, to); //this gives error
ListView listView = (ListView)l2.findViewById(R.id.listView1);
listView.setAdapter(dataAdapter);
return l2;
}
}