ok, well I created my own custumadapter class for using in a listview, and I am getting a nullpointerexception on line 178 that says "if(inputSearch.getText().toString().isEmpty())"
can someone help me see why I am getting this?
here is my code:
package com.example.student_lists;
import java.util.ArrayList;
import java.util.Locale;
import com.resources.student_list.Student;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
EditText inputSearch;
// static ListView lv;
// static EditText inputSearch;
//static MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
private class MyListAdapter extends ArrayAdapter<Student> implements Filterable{
private final Context context;
public ArrayList<Student> displayValues;
public ArrayList<Student> originalValues;
public MyListAdapter(Context context, int textViewResourceId, ArrayList<Student> values) {
super(context, textViewResourceId, values);
this.context = context;
this.displayValues = values;
this.originalValues = (ArrayList<Student>) values.clone();
}
public int getCount(){
return this.displayValues.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//----This method sets each row of the list individually----
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.list_view, parent, false);
if(displayValues.size() > 0)
{
Student student = displayValues.get(position);
// //Fill Name
TextView name = (TextView) itemView.findViewById(R.id.contactName);
name.setText(student.getFirstName() + " " + student.getLastName());
}
return itemView;
}
public Filter getFilter() {
Filter contactFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<Student> filteredList = new ArrayList<Student>();
//Filter the list
if(constraint != null && originalValues !=null) {
if(!constraint.toString().isEmpty())
{
String constraintLowerCase = constraint.toString().toLowerCase();
for(Student c: originalValues)
{
String cName = c.getFirstName().toLowerCase() ;
String cLName = c.getLastName().toLowerCase();
if(cName.startsWith(constraintLowerCase) || cLName.startsWith(constraintLowerCase))
{
//Add the row to the list if filtered items
filteredList.add(c);
}
}
}
//Important steps to store the filtered list
filterResults.values = filteredList;
filterResults.count = filteredList.size();
}
return filterResults;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence contraint, FilterResults results) {
if (results.count > 0)
{
//Display the filtered list
MyListAdapter.this.displayValues = (ArrayList<Student>) results.values;
notifyDataSetChanged();
}
else
{
if(inputSearch.getText().toString().isEmpty())
{
//Display the original list
MyListAdapter.this.displayValues = (ArrayList<Student>) MyListAdapter.this.originalValues.clone();
}
else
{
//Display an empty list
MyListAdapter.this.displayValues.clear();
}
notifyDataSetInvalidated();
}
}
};
return contactFilter;
}
}
#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(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
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";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 0:
case 1:
Student andres = new Student();
andres.setFirstName("Andres");
andres.setLastName("Blanco");
Student ondria = new Student();
ondria.setFirstName("Ondria");
ondria.setLastName("Arias");
ArrayList<Student> studentList = new ArrayList<Student>();
studentList.add(andres);
studentList.add(ondria);
MainActivity mainactivity = new MainActivity();
ListView lv = (ListView) rootView.findViewById(R.id.list);
final MyListAdapter adapter = mainactivity.new MyListAdapter(getActivity(), R.layout.list_view, studentList);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
EditText inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
return rootView;
case 2:
}
return rootView;
}
}
}
You need to initialise your EditText first like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
EditText inputSearch = (EditText) this.findViewById(R.id.inputSearch);
}
Then, instead of:
if (inputSearch.getText().toString().isEmpty())
You should do this:
if (inputSearch.getText() != null) {
// Do something
} else {
// Do something else
}
I don't see where you've initialized inputSearch. If you don't initialize it, then it will be null and you will get a NullPointerException when you call getText() on it.
EDIT
You have this line:
EditText inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
This is only a local variable and is not the same inputSearch as the one in publishResults Change this line to
inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
Related
i'm very new to Android programming, and i'm trying to make the instantiateItem on my SlidingTabsBasicFragment class, to return the fragment of my ConversationsFragment.
In my understanding, my Class ConversationsFragment returns a fragment, that would be instantiated. But instead, nothing shows at the second page.
I'm using the SlidingTabsBasic sample to make this:
Main Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("Logs", "first");
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
transaction.replace(R.id.sample_content_fragment, fragment);
//ConversationsFragment fragment = new ConversationsFragment();
//transaction.replace(R.id.sample_content_fragment, new ConversationsFragment());
transaction.commit();
}
}
SlidingTabsBasicFragment:
package com.example.android.slidingtabsbasic;
import com.example.android.common.logger.Log;
import com.example.android.common.view.SlidingTabLayout;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.TextView;
/**
* A basic sample which shows how to use {#link com.example.android.common.view.SlidingTabLayout}
* to display a custom {#link ViewPager} title strip which gives continuous feedback to the user
* when scrolling.
*/
public class SlidingTabsBasicFragment extends Fragment {
static final String LOG_TAG = "SlidingTabsBasicFragment";
/**
* A custom {#link ViewPager} title strip which looks much like Tabs present in Android v4.0 and
* above, but is designed to give continuous feedback to the user when scrolling.
*/
private SlidingTabLayout mSlidingTabLayout;
/**
* A {#link ViewPager} which will be used in conjunction with the {#link SlidingTabLayout} above.
*/
private ViewPager mViewPager;
/**
* Inflates the {#link View} which will be displayed by this {#link Fragment}, from the app's
* resources.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sample, container, false);
}
// BEGIN_INCLUDE (fragment_onviewcreated)
/**
* This is called after the {#link #onCreateView(LayoutInflater, ViewGroup, Bundle)} has finished.
* Here we can pick out the {#link View}s we need to configure from the content view.
*
* We set the {#link ViewPager}'s adapter to be an instance of {#link SamplePagerAdapter}. The
* {#link SlidingTabLayout} is then given the {#link ViewPager} so that it can populate itself.
*
* #param view View created in {#link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
*/
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// BEGIN_INCLUDE (setup_viewpager)
// Get the ViewPager and set it's PagerAdapter so that it can display items
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new CustomPagerAdapter(getFragmentManager(),getActivity()));
// END_INCLUDE (setup_viewpager)
// BEGIN_INCLUDE (setup_slidingtablayout)
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
// END_INCLUDE (setup_slidingtablayout)
}
// END_INCLUDE (fragment_onviewcreated)
public class CustomPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public CharSequence getPageTitle(int position) {
return "Item " + (position + 1);
}
#Override
public Fragment getItem(int position) {
if(position==0){
// return fragment
}else{
ConversationsFragment fragment = new ConversationsFragment();
return fragment;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
}
And this is my ConversationsFragment:
public class ConversationsFragment extends Fragment implements AbsListView.OnItemClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private List conversationsListItemList; // at the top of your fragment listW
private ListAdapter mAdapter;
// TODO: Rename and change types of parameters
public static ConversationsFragment newInstance(String param1, String param2) {
ConversationsFragment fragment = new ConversationsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ConversationsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
conversationsListItemList = new ArrayList();
conversationsListItemList.add(new ConversationsListItem("Example 1","conversa"));
conversationsListItemList.add(new ConversationsListItem("Example 2","conversa"));
conversationsListItemList.add(new ConversationsListItem("Example 3","conversa"));
mAdapter = new ConversationsListAdapter(getActivity(), conversationsListItemList);
/* mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_conversations, container, false);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(String id);
}
}
Screenshots:
First Screen:
https://goo.gl/photos/Ze5ThZgevGaALDj47
Second Screen:
https://goo.gl/photos/x7JPnESAtZsBT5DC8
And now this errors appears:
06-16 12:32:58.946 12228-12228/com.example.android.slidingtabsbasic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.slidingtabsbasic, PID: 12228
java.lang.NullPointerException
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:417)
at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:412)
at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:99)
I think problem with your code is returning View and Fragment
below code worked for me
public class CustomPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public CustomPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public CharSequence getPageTitle(int position) {
return "" + tabsTitle[position];
}
#Override
public Fragment getItem(int position) {
if(position==0){
// return fragment
}else{
ConversationsFragment fragment = new ConversationsFragment();
return fragment;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
I have a working ListView, in a fragment and when the ListItem is clicked
I want to link the data to a new Activity. I am getting an error that my db object cannot be cast to the db Cursor
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.mlaffan.giftpal.sqlite.adapter.PersonAdapter;
import com.mlaffan.giftpal.sqlite.db.DatabaseHelper;
import com.mlaffan.giftpal.sqlite.db.Person;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
public PersonAdapter personAdapter;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* four primary sections of the app. We use a {#link android.support.v4.app.FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
/**
* The {#link ViewPager} that will display the four primary sections of the app, one at a
* time.
*/
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelper dbHelp = new DatabaseHelper(getApplicationContext());
// Create the adapter that will return a fragment for each of the four primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LaunchpadSectionFragment();
case 1:
return new AddPeopleFragment();
case 2:
return new PeopleSectionFragment();
default:
return new SnapGiftFragment();
// default:
// The other sections of the app are dummy placeholders.
// Fragment fragment = new DummySectionFragment();
// Bundle args = new Bundle();
// args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
// fragment.setArguments(args);
// return fragment;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Events";
} else if (position == 1) {
return "Add People";
} else if (position == 2) {
return "Your People";
} else {
return "Snap Gift";
}
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
// Demonstration of navigating to external activities.
rootView.findViewById(R.id.demo_external_activity)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create an intent that asks the user to pick a photo, but using
// FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
// the application from the device home screen does not return
// to the external activity.
Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
externalActivityIntent.setType("image/*");
externalActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(externalActivityIntent);
}
});
// link to Profiles Activitys.
rootView.findViewById(R.id.profiles_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), ProfileActivity.class);
startActivity(intent);
}
});
return rootView;
}
}
/**
* A fragment lets the user create a new profile.
*/
public static class AddPeopleFragment extends Fragment {
private String sex = "male";
private EditText firstName;
private EditText lastName;
private DatePicker birthday;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_people, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, final Bundle bundle) {
super.onViewCreated(view, bundle);
firstName = (EditText) view.findViewById(R.id.firstName);
lastName = (EditText) view.findViewById(R.id.lastName);
RadioButton male = (RadioButton) view.findViewById(R.id.male);
RadioButton female = (RadioButton) view.findViewById(R.id.female);
birthday = (DatePicker) view.findViewById(R.id.datePicker);
Button button = (Button) view.findViewById(R.id.button);
male.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sex = "male";
}
});
female.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sex = "female";
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fName = firstName.getText().toString();
String lName = lastName.getText().toString();
int day = birthday.getDayOfMonth();
int month = birthday.getMonth();
int year = birthday.getYear();
Person person = new Person();
person.setFirstName(fName);
person.setLastName(lName);
person.setSex(sex);
person.setBirthday("" + day + "/" + month + "/" + year);
DatabaseHelper dbHelper = new DatabaseHelper(getActivity().getApplicationContext());
dbHelper.addPerson(person);
Toast.makeText(getActivity(), "Profile added!", Toast.LENGTH_SHORT).show();
if (PeopleSectionFragment.adapter != null) {
PeopleSectionFragment.adapter.add(person);
}
}
});
}
}
/**
* A fragment that contains a list of profiles.
*/
public static class PeopleSectionFragment extends Fragment {
public static PersonAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_people, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle bundle) {
super.onViewCreated(view, bundle);
DatabaseHelper dbHelp = new
DatabaseHelper(getActivity().getApplicationContext());
ArrayList<Person> people = dbHelp.getPeople();
adapter = new PersonAdapter(getActivity().getApplicationContext(),
R.layout.fragment_people_list_item, people);
ListView listView = (ListView) getActivity().findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new ItemClicked());
}
class ItemClicked implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Person person = adapter.getItem(position);
Log.i("ItemClicked", person.getFirstName());
// When a listitem is clicked
Intent intent = new Intent(getActivity(), Profile.class);
Cursor cursor = (Cursor) person;
intent.putExtra("PERSON_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
}
}
public static class SnapGiftFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_snap_gift, container, false);
return rootView;
}
}
}
This code seems to be where the trouble is;
Intent intent = new Intent(getActivity(), Profile.class);
Cursor cursor = (Cursor) person;
intent.putExtra("PERSON_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
This is the error message;
05-05 12:27:54.575 2231-2231/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mlaffan.giftpal, PID: 2231
java.lang.ClassCastException: com.mlaffan.giftpal.sqlite.db.Person cannot be cast to android.database.Cursor
at com.mlaffan.giftpal.MainActivity$PeopleSectionFragment$ItemClicked.onItemClick(MainActivity.java:306)
at android.widget.AdapterView.performItemClick(AdapterView.java:300)
at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044)
at android.widget.AbsListView$3.run(AbsListView.java:3833)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Here is the target activity;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
import com.mlaffan.giftpal.sqlite.db.DatabaseHelper;
/**
* Created by Mark on 05/05/2015.
*/
public class Profile extends Activity {
protected TextView profileFirst;
protected TextView profileLast;
protected TextView profileBirthday;
protected TextView profileSex;
protected int profileId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_view);
profileId = getIntent().getIntExtra("PERSON_ID", 0);
SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT _id, firstName, lastName, sex, birthday FROM people WHERE _id = ?",
new String[]{""+profileId});
if (cursor.getCount() == 1){
cursor.moveToFirst();
profileFirst = (TextView) findViewById(R.id.profileFirst);
profileFirst.setText(cursor.getString(cursor.getColumnIndex("firstName")));
profileLast = (TextView) findViewById(R.id.lastName);
profileLast.setText(cursor.getString(cursor.getColumnIndex("lastName")));
profileSex = (TextView) findViewById(R.id.profileSex);
profileSex.setText(cursor.getString(cursor.getColumnIndex("sex")));
profileBirthday = (TextView) findViewById(R.id.profileBirthday);
profileBirthday.setText(cursor.getString(cursor.getColumnIndex("birthday")));
}
}
}
Apologies if this is a messy one, if I need to give more information please ask.
Extend your Person class as Serializable and than you can try this way:
Person person = (Person)adapter.getItem(position);
Intent intent = new Intent(getActivity(), Profile.class);
intent.putExtra("person", person);
startActivity(intent);
Now in your Profile activity, do this way:
Person person;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_view);
person = (Person) getIntent().getSerializableExtra("person");
profileFirst = (TextView) findViewById(R.id.profileFirst);
profileFirst.setText(person.firstName);
profileLast = (TextView) findViewById(R.id.lastName);
profileLast.setText(person.lastName");
...
...
}
ok, here is the main activity which is suppose to show the 2 tabs.
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
// SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position); }
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#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(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
if (tab.getPosition() == 0) {
MyFriendsListFragment simpleListFragment = new MyFriendsListFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.pager, simpleListFragment).commit();
}
else if (tab.getPosition() == 1) {
MyFriendsListFragment simpleListFragment = new MyFriendsListFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.pager, simpleListFragment).commit();
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
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";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
Bundle args = getArguments();
textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
return textView;
}
}
}
and here is the class thats being called when one of the tabs is being pressed, right now both tabs are supposed to show the same thing, because both of them call the same class.
*public class MyFriendsListFragment extends ListFragment {
private ArrayList<Student> studentList = new ArrayList<Student>();
private ListView lv;
private EditText inputSearch;
public MyFriendsListFragment() {
Student andres = new Student();
andres.setFirstName("Andres");
andres.setLastName("Blanco");
Student ondria = new Student();
ondria.setFirstName("Ondria");
ondria.setLastName("Arias");
studentList.add(andres);
studentList.add(ondria);
}
private class MyListAdapter extends ArrayAdapter<Student> implements Filterable{
private final Context context;
public ArrayList<Student> displayValues;
public ArrayList<Student> originalValues;
public MyListAdapter(Context context, int textViewResourceId, ArrayList<Student> values) {
super(context, textViewResourceId, values);
this.context = context;
this.displayValues = values;
this.originalValues = (ArrayList<Student>) values.clone();
}
public int getCount(){
return this.displayValues.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//----This method sets each row of the list individually----
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.list_view, parent, false);
if(displayValues.size() > 0)
{
Student student = displayValues.get(position);
//Fill Name
TextView name = (TextView) itemView.findViewById(R.id.contactName);
name.setText(student.getFirstName() + student.getLastName());
}
return itemView;
}
public Filter getFilter() {
Filter contactFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<Student> filteredList = new ArrayList<Student>();
//Filter the list
if(constraint != null && originalValues !=null) {
if(!constraint.toString().isEmpty())
{
String constraintLowerCase = constraint.toString().toLowerCase();
for(Student c: originalValues)
{
String cName = c.getFirstName().toLowerCase() ;
String cLName = c.getLastName().toLowerCase();
if(cName.startsWith(constraintLowerCase) || cLName.startsWith(constraintLowerCase))
{
//Add the row to the list if filtered items
filteredList.add(c);
}
}
}
//Important steps to store the filtered list
filterResults.values = filteredList;
filterResults.count = filteredList.size();
}
return filterResults;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence contraint, FilterResults results) {
if (results.count > 0)
{
//Display the filtered list
MyListAdapter.this.displayValues = (ArrayList<Student>) results.values;
notifyDataSetChanged();
}
else
{
if(inputSearch.getText().toString().isEmpty())
{
//Display the original list
MyListAdapter.this.displayValues = (ArrayList<Student>) MyListAdapter.this.originalValues.clone();
}
else
{
//Display an empty list
MyListAdapter.this.displayValues.clear();
}
notifyDataSetInvalidated();
}
}
};
return contactFilter;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
try{
lv = (ListView) rootView.findViewById(R.id.list);
inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
MyListAdapter adapter = new MyListAdapter(getActivity(), R.layout.list_view, studentList);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
}
catch (Exception e){
Log.e("Error!!!!!", "00");
}
return rootView;
}
#Override
public void onListItemClick(ListView list, View v, int pos, long id) {
try{
Student clickedStudent = studentList.get(pos);
int position = pos;
Intent intent = new Intent(getActivity(), ShowStudentActivity.class);
Log.e("CINTENT","CREATED!!!");
intent.putExtra("clickedContact",clickedStudent);
intent.putExtra("officialList",studentList);
intent.putExtra("position",position);
Log.e("putExtra","Passed");
startActivity(intent);
Log.e("Start activity","passed");
}
catch (Exception e){
Log.e("Catch!","CATCH!!!!");
}
}
}*
When i run it it just crashes and gives me an error saying that there needs to be something inside the listview, but i think i am filling the listview in the oncreateview method. please help me, been at this for a week searching online and have not found any solution, thx!
I am trying to make the Contact tab in my app to list the users address book's name and phone number, however when I set the adapter for contactlist the app no longer shows its tabs and the fragment is empty.
Code:
package com.spgrn.smsim;
import java.util.ArrayList;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
String phoneNumber;
ListView contactlist;
ArrayList <String> aa= new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactlist= (ListView) findViewById(R.id.contactv);
getNumber(this.getContentResolver());
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
Log.v("I", "curtab="+ mSectionsPagerAdapter.getCount() + "i=" + i);
if (i != 1)
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this),
false);
if (i == 1)
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this),
true);
}
}
public void getNumber(ContentResolver cr)
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(name + phoneNumber);
aa.add(name + "\n" + phoneNumber);
}
Log.v("Contacts", "Total= " + phones.getCount());
phones.close();// close cursor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,aa);
contactlist.setAdapter(adapter);
}
#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;
}
if (id == R.id.action_compose) {
Intent intent = new Intent(this, NewMessage.class);
this.startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position){
case 0:
Fragment fragmentContacts = new FragmentContacts();
return fragmentContacts;
case 1:
Fragment fragmentMessages = new FragmentMessages();
return fragmentMessages;
case 2:
Fragment fragmentAccounts = new FragmentAccounts();
return fragmentAccounts;
}
return null;
}
#Override
public int getCount() {
// Show 5 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
//Make fragments for each tab
public static class FragmentContacts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentContacts() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
return rootView;
}
}
public static class FragmentMessages extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentMessages() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,
container, false);
return rootView;
}
}
public static class FragmentAccounts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentAccounts() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_accounts,
container, false);
return rootView;
}
}
//End of Tab Fragments
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return 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;
}
}
}
Also, in the debugger I noticed the main activity was suspended due to a run time exception. Here is the stack:
Thread [<1> main] (Suspended (exception RuntimeException))
<VM does not provide monitor information>
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2195
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2245
ActivityThread.access$800(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 135
ActivityThread$H.handleMessage(Message) line: 1196
ActivityThread$H(Handler).dispatchMessage(Message) line: 102
Looper.loop() line: 136
ActivityThread.main(String[]) line: 5017
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 515
ZygoteInit$MethodAndArgsCaller.run() line: 779
ZygoteInit.main(String[]) line: 595
XposedBridge.main(String[]) line: 126
NativeStart.main(String[]) line: not available [native method]
Thanks!
Edit: Looking more, I think the list needs to be generated in the fragments class, but I am not sure what to do with the context. I keep getting a NullPointerException.
Code:
public static class FragmentContacts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentContacts() {
}
Context context;
String phoneNumber;
ListView contactlist;
ArrayList <String> aa= new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
contactlist = (ListView) rootView.findViewById(R.id.contactv);
getNumber(context.getContentResolver());
return rootView;
}
public void getNumber(ContentResolver cr)
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(name + phoneNumber);
aa.add(name + "\n" + phoneNumber);
}
Log.v("Contacts", "Total= " + phones.getCount());
phones.close();// close cursor
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
.getApplicationContext(),
android.R.layout.simple_list_item_1,aa);
contactlist.setAdapter(adapter);
}
}
write
context=container.getContext();
in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts,
container, false);
contactlist = (ListView) rootView.findViewById(R.id.contactv);
context=container.getContext();
getNumber(context.getContentResolver());
return rootView;
}
I've written a few listView activities, as a proof of concept for myself that I could do it. Now, I'm having trouble loading a listView activity into a single tab for an app with multiple tabs, that allows both swiping and tab selection for navigation. I get the error "The constructor ListView_Adapter(MainActivity.DummySectionFragment) is undefined" when I try to write the code for it. I'm a beginner, and I've lurked pretty hard here for the past few days. Any help is appreciated.
TL;DR : I'm a n00b, and I can't figure out this problem.
My Custom List Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomListViewAdapter extends ArrayAdapter<String> {
public CustomListViewAdapter (Context c) {
super(c, R.layout.list_cell);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ListView_Text holder = null;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_cell, parent, false);
holder = new ListView_Text(row);
row.setTag(holder);
}
else
{
holder = (ListView_Text) row.getTag();
}
holder.populateFrom(getItem(position));
return row;
}
static class ListView_Text {
private TextView cell_name = null;
ListView_Text(View row) {
cell_name = (TextView) row.findViewById(R.id.list_cell_name);
}
void populateFrom(String index) {
cell_name.setText(index);
}
}
}
My Main Activity
import java.util.Locale;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import com.example.twigglebeta2.ListView_Adapter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private static ListView_Adapter listViewAdapter;
private ListView listView;
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create adapter
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Switch tab selection to match current page when swiped
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Create a tab for each 'count' in the activity from getCount()
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
Tab thisTab = actionBar.newTab();
thisTab.setText(mSectionsPagerAdapter.getPageTitle(i));
thisTab.setTabListener(this);
actionBar.addTab(thisTab);
}
}
#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(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
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";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
//The constructor ListView_Adapter(MainActivity.DummySectionFragment) is undefined
listViewAdapter = new ListView_Adapter(this);
ListView listView = (ListView) rootView.findViewById(R.id.listView1);
for (int i=0;i<20;i++)
{
listViewAdapter.add("this Index : "+i);
}
return listView;
}
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Instead of listViewAdapter = new ListView_Adapter(this);, you should instead try listViewAdapter = new ListView_Adapter(getActivity().getBaseContext());
The Issue is that you are passing a Fragment to the constructor, and not an Activity context.