populating autoCompleteTextView with ArrayAdapter - android

I am trying to populate data into autoCompleteTextView using ArrayAdapter whenever I run the application it tells me "Unfortunately the application has stopped". This part is an a gosh for me "adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, words);
edit.setAdapter(adapter);" What have i done wrong? Please help
public class MainActivity extends ActionBarActivity implements TextWatcher
{
private static final String DB_NAME = "mydata.sqlite3";
ArrayAdapter<String> adapter;
private SQLiteDatabase database;
private ArrayList<String> words;
private AutoCompleteTextView edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
database = dbOpenHelper.openDataBase();
edit = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
setWordList();
}
private void setWordList()
{
words = new ArrayList<String>();
Cursor friendCursor = database.rawQuery("SELECT * FROM WordTableList", null);
friendCursor.moveToFirst();
if(!friendCursor.isAfterLast())
{
do
{
String myWord = friendCursor.getString(1);
words.add(myWord);
} while (friendCursor.moveToNext());
}
friendCursor.close();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, words);
edit.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;
}
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;
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
}

Related

SearchView in ActionBar with more fragment on android

I need Add SearchBar in ActionBar handle with more Fragments like whatsApp
when Search in Tab chats get data and when Search in Tab Status get another data
How do This?This is My Code there is 3 tabs i need every tab there is SearchView
This Activity which there is on Fragments
public class ActivityForIncludeFragments extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_for_include_fragments);
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
CategoryAdapter adapter = new CategoryAdapter(this,getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
invalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem menuItemAddData = menu.findItem(R.id.add_data);
MenuItem menuItemActionSearch = menu.findItem(R.id.action_search);
menuItemAddData.setVisible(false);
menuItemActionSearch.setVisible(false);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.add_stocking_warehouse:
Intent intent = new Intent(ActivityForIncludeFragments.this,StockingWarehouse.class);
startActivity(intent);
break;
case R.id.add_reportes:
Intent intentReport = new Intent(ActivityForIncludeFragments.this,TableDaliyMovmentes.class);
startActivity(intentReport);
break;
}
return super.onOptionsItemSelected(item);
}
}
and This Fragment there is the data
public class AddPremissionFragment extends Fragment implements
LoaderManager.LoaderCallbacks<ArrayList<ItemsStore>>
,SearchView.OnQueryTextListener {
public AddPremissionFragment() {
// Required empty public constructor
}
public static final String ID_PERMISSION = "id";
public static final String NAME_PERMISION = "namePErmission";
public static final String NOTES_PERMISSION = "notes";
public static final String DIALOG_PERMISSION = "dialogPermission";
FloatingActionButton fab_add_permission;
ListView mListView;
public static AdapterAddPermission adapterAddPermission;
TaskDbHelper dbHelper;
ArrayList<ItemsStore> itemsPermissions = new ArrayList<ItemsStore>();
private ProgressBar progressBarPermission;
//Identifier for the category dataloader;
public static final int PERMISSION_LOADER = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_add_premission, container, false);
TextView namePremission = (TextView)view.findViewById(R.id.ETTypeStore);
dbHelper = new TaskDbHelper(getActivity());
mListView = (ListView) view.findViewById(R.id.listViewAddPermission);
progressBarPermission =(ProgressBar)view.findViewById(R.id.progressBarPermission);
adapterAddPermission = new AdapterAddPermission(getContext(), itemsPermissions);
View emptyView = view.findViewById(R.id.empty_view_permission);
mListView.setEmptyView(emptyView);
mListView.setAdapter(adapterAddPermission);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getContext(), "Click :"+ position, Toast.LENGTH_SHORT).show();
ItemsStore itemSPermision = itemsPermissions.get(position);
Bundle bundle = new Bundle();
bundle.putInt(ID_PERMISSION, itemSPermision.getId());
bundle.putString(NAME_PERMISION, itemSPermision.getNamePermission());
bundle.putString(NOTES_PERMISSION, itemSPermision.getNotes());
// startActivity(intent);
// long id = cursor.getLong(cursor.getColumnIndex(TaskContract.TaskEntry._ID));
EditPermissionFragment f = new EditPermissionFragment();
f.setArguments(bundle);
f.show(getFragmentManager(),DIALOG_PERMISSION);}});
// namePremission.setText("Name Permission");
fab_add_permission = (FloatingActionButton)view.findViewById(R.id.fab_add_permission);
fab_add_permission.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new EditPermissionFragment().show(getFragmentManager(),DIALOG_PERMISSION);
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Kick off the loader
getActivity().getSupportLoaderManager().initLoader(PERMISSION_LOADER, null, this);
}
#Override
public Loader<ArrayList<ItemsStore>> onCreateLoader(int id, Bundle args) {
return new LoaderPErmission(getContext().getApplicationContext(),itemsPermissions,dbHelper);
}
#Override
public void onLoadFinished(Loader<ArrayList<ItemsStore>> loader, ArrayList<ItemsStore> data) {
progressBarPermission.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
adapterAddPermission.swapData(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<ItemsStore>> loader) {
adapterAddPermission.swapData(Collections.<ItemsStore>emptyList());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(this);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
itemsPermissions = dbHelper.getAllItemsPermissionBySearch(newText);
if (itemsPermissions !=null){
adapterAddPermission.setFilter(itemsPermissions);
// getSupportLoaderManager().restartLoader(Daily_LOADER,null,this);
}
return false;
}
}
Please check which fragment is visible using this
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment != null && fragment.isVisible()) {
if (fragment instanceof ChatFragment) {
....
}
else { }
}

Fragment is showing but not attached to activity

Hi i am working in an app, in which:
View pager is there on an activity.
On that view pager i am showing 2 fragments(frag1 and frag2).
on button click on frag1 we have added one more fragment(lets say frag3).
and on back press on frag3 i come back on frag1.
Issue:
the issue is when i come back to frag1 from frag3 on back press, sometimes frag1 is not attached to the activity.
i am not able to figure out how this is happening.
if this is happening then what is the solution so i can stop activity to detach the frag1 or re-initialize the frag1 again.
Please help.
This code may help you
public class PageAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final int[] PAGER = new int[] {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4
};
private int mCount = PAGER.length;
public PagerFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new PagerFragment(PAGER[position]);
}
#Override
public int getIconResId(int index) {
return ICONS[index % PAGER.length];
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
Defining Fragments
public final class PagerFragment extends Fragment {
private static final String KEY_CONTENT = "PagerFragment:Content";
int imageSource;
public PagerFragment(int imageSource) {
this.imageSource = imageSource;
}
public PagerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
imageSource = savedInstanceState.getInt(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.indicatorpage, null);
ImageView image = (ImageView) root.findViewById(R.id.pagerImage);
image.setImageResource(imageSource);
setRetainInstance(true);
return root;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_CONTENT, imageSource);
}
}
MainActivity Class
public class MainActivity extends FragmentActivity {
PagerFragmentAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new PagerFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
System.out.println("selected page is :" + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
CirclePageIndicator mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
mIndicator.setRadius(7 * density);
mIndicator.setPageColor(0x00000000);
mIndicator.setFillColor(0xFFFFFFFF);
mIndicator.setStrokeColor(0xFFFFFFFF);
mIndicator.setStrokeWidth(1 * density);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

I can't save instance of fragment to not restart after screen rotation

My fragment's code looks like this:
public class AllIssuesFragment extends Fragment {
#Bind(R.id.list_all_issues) ListView mListAllIssues;
IssuesGetter ai;
ArrayAdapter<IssuesResponse.Issue> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_all_issues, container, false);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
setRetainInstance(true);
SharedPreferences user_data = this.getActivity().getSharedPreferences("user_data", Context.MODE_PRIVATE);
UserManager.getInstance().setUsername(user_data.getString("username", null));
UserManager.getInstance().setPassword(user_data.getString("password", null));
if(UserManager.getInstance().getUsername() == null || UserManager.getInstance().getPassword() == null) {
Intent intent = new Intent(getActivity(), ChangeUserActivity.class);
startActivity(intent);
}
else {
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1);
if(savedInstanceState == null) {
getIssues(Constants.URI + Constants.ISSUES + Constants.OFFSET + 0);
}
mListAllIssues.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = firstVisible + visibleCount >= totalCount;
if (loadMore && ai.getStatus() == AsyncTask.Status.FINISHED) {
getIssues(Constants.URI + Constants.ISSUES + Constants.OFFSET + totalCount);
mListAllIssues.setSelection(totalCount);
}
}
});
}
}
private void getIssues(String url) {
ai = new IssuesGetter(new AsyncCallback<IssuesResponse>() {
#Override
public void onSuccess(IssuesResponse response) {
int index = mListAllIssues.getFirstVisiblePosition();
View v = mListAllIssues.getChildAt(0);
int top = (v == null)? 0 : v.getTop();
adapter.addAll(response.getIssues());
adapter.notifyDataSetChanged();
mListAllIssues.setAdapter(adapter);
mListAllIssues.setSelectionFromTop(index, top);
}
#Override
public void onError() {
Intent intent = new Intent(getActivity(), ChangeUserActivity.class);
startActivity(intent);
}
});
ai.execute(url);
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Bind(R.id.viewpager) ViewPager viewPager;
#Bind(R.id.tabs) PagerSlidingTabStrip tabStrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
viewPager.setAdapter(new MainActivityPagerAdapter(getSupportFragmentManager()));
tabStrip.setViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_change_user) {
Intent intent = new Intent(this, ChangeUserActivity.class);
this.startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
I've tried to use setRetainInstance(true) and check if the savedInstanceState equals null, but it didn't solve my problem. I am stuck :(
My Asynctask returns result using call back.
I see the problem here:
public void onCreate() {
//..
viewPager.setAdapter(new MainActivityPagerAdapter(getSupportFragmentManager()));
tabStrip.setViewPager(viewPager);
}
This method is called each time activity is recreated. And what it does is creates new adapter which creates brand new fragments. And that is a problem. Because your activity doesn't control creation of fragments. That is neccessary in order to retain fragments.
I suggest you to save state of fragment in onSaveInstanceState() callback and restore it in onCreateView(). Note that you don't need to save state of UI elements just variables of fragment class. UI elements save their state automatically if they have unique id.
EDIT:
My suggestion:
public class AllIssuesFragment extends Fragment {
private List<String> issues;
// ..
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ..
if (null != savedInstanceState) {
issues = savedInstanceState.getStringArray("issues");
} else {
issues = new List<>();
}
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, issues);
// ..
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArray("issues", issues);
}
private void getIssues(String url) {
// ..
ai = new IssuesGetter(new AsyncCallback<IssuesResponse>() {
#Override
public void onSuccess(IssuesResponse response) {
// ..
//adapter.addAll(response.getIssues());
issues.addAll(response.getIssues());
adapter.notifyDataSetChanged();
// ..
}
};
// ..
}
}

FragmentStatePagerAdapter and ViewPager: Fragments instantiate out of order

I am trying to use FragmentStatePagerAdapter with ViewPager to achieve a sequential slide scroll view (similar to most pdf readers). However, while running the code, the following is happening:
When the activity becomes visible, the first page is instantiated with a different (2nd) page's value. However, when scrolled to some other page and then back to page 1, the page displays default text from layout file.
Only 2nd and 2nd to last pages instantiate with the passed value (that too with values from other pages, not their own). Rest of the pages display default text from layout file.
On debugging, I noticed that the index/currentItemNumber changes when ViewPager.populate() calls ViewPager.addNewItem(). Ever more strange is the fact that setText() is called on the TextView (part of fragment layout), but text does not change from the default text.
Am I missing something?
Here is the code below:
MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private ViewPager mPager;
private Button mButtonFirst;
private Button mButtonPrev;
private Button mButtonGoTo;
private Button mButtonNext;
private Button mButtonLast;
private TextView mPageCount;
private EditText mPageNumber;
private TextView mError;
private int mNumScreens;
private int mCurrScreen;
private MyPagerAdapter mMyPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpViews();
setUpListeners();
setUpPager();
}
private void setUpViews() {
mPager = (ViewPager) findViewById(R.id.my_pager);
// Get other view handles...
mError = (TextView) findViewById(R.id.error_details);
}
private void setUpListeners() {
// Set this class as click handler for all buttons
}
private void setUpPager() {
String[] strings = new String[] {
"1",
"2",
"3",
"4",
"5",
"6"
};
// Success!
// Set adapter and update views
mMyPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), strings);
mPager.setAdapter(mMyPagerAdapter);
mNumScreens = strings.length;
mPageCount.setText("/" + Integer.toString(mNumScreens));
mCurrScreen = -1;
GoToScreen(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// Handle options
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button_first:
GoToScreen(1);
break;
case R.id.button_prev:
GoToScreen(mCurrScreen - 1);
break;
case R.id.button_goto:
{
int screen;
boolean reset = false;
try {
screen = Integer.parseInt(mPageNumber.getText().toString());
reset = !SetToScreen(screen);
} catch (NumberFormatException e) {
e.printStackTrace();
reset = true;
}
if(reset) {
mPageNumber.setText(Integer.toString(mCurrScreen));
}
}
break;
case R.id.button_next:
GoToScreen(mCurrScreen + 1);
break;
case R.id.button_last:
GoToScreen(mNumScreens);
break;
}
}
private void GoToScreen(int screen) {
if(SetToScreen(screen)) {
mPageNumber.setText(Integer.toString(mCurrScreen));
}
}
private boolean SetToScreen(int screen) {
// Switch to a valid screen
if(screen >= 1 && screen <= mNumScreens && mCurrScreen != screen) {
mPager.setCurrentItem(screen - 1, false);
// Handle button visibility
// Update current screen
mCurrScreen = screen;
return true;
}
return false;
}
MyPagerAdapter.java
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private final String[] mStrings;
public MyPagerAdapter(FragmentManager fm, String[] strings) {
super(fm);
mStrings = strings;
}
#Override
public int getCount() {
return mStrings.length;
}
#Override
public Fragment getItem(int position) {
return ScreenFragment.newInstance(mStrings[position]);
}
}
ScreenFragment.java
public class ScreenFragment extends Fragment {
private static final String ARG_SCREEN_STRING= "screen_string";
private String mScreenInfo;
private TextView mStatementLabel;
public static ScreenFragment newInstance(String screenString) {
ScreenFragment fragment = new ScreenFragment();
Bundle args = new Bundle();
args.putString(ARG_SCREEN_STRING, screenString);
fragment.setArguments(args);
return fragment;
}
public ScreenFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mScreenInfo = getArguments().getString(ARG_SCREEN_STRING);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_screen, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setUpViews();
setUpFields();
}
private void setUpFields() {
mStatementLabel.setText(mScreenInfo);
}
private void setUpViews() {
mStatementLabel = (TextView) getActivity().findViewById(R.id.qnr_screen_statement);
}
}
The problem was solved when I moved calls to setUpViews() and setUpFields() to onCreateView() from onActivityCreated(), with little modifications. This is how the new onCreateView() looks like (I moved the content of the above mentioned functions here)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_screen, container, false);
mStatementLabel = (TextView) v.findViewById(R.id.qnr_screen_statement);
mStatementLabel.setText(mScreenInfo);
return v;
}
I am yet to figure out why that was causing the problem. Will update if I find anything.

Android don't load fragment (with Activity). Why?

I'm trying to go to a specific fragment and I intialisate this in Activity. But I don't get any error on my screen but on my device, my app is stopped running, he doesn't go in Fragment. What can be the problem? Thanx for you help. Below you find my code:
public class SubCatActivity extends Activity {
int hoofdCat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcat);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new SubCatFragment())
.commit();
}
hoofdCat = Integer.parseInt(getIntent().getStringExtra("hoofdCat"));
}
public int getHoofdCat(){return hoofdCat;}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.info, 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);
}
My Fragment:
public class SubCatFragment extends Fragment implements SubCatFragmentInteractionListener {
private SubCatFragmentInteractionListener mListener;
public SubCatFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_subcat, container, false);
ListView lstSubcat = (ListView) rootView.findViewById(R.id.lvSubcat);
ArrayList<String> subcat = new ArrayList<String>();
SubCatActivity activity = (SubCatActivity)getActivity();
int hoofdcat =activity.getHoofdCat();
DBAdapter db = new DBAdapter(getActivity().getBaseContext());
db.open();
Cursor c = db.getAllSubcat(hoofdcat);
if(c.moveToFirst())
{
do{
subcat.add(c.getString(1));
}while (c.moveToNext());
}
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, subcat);
lstSubcat.setAdapter(adapter);
lstSubcat.setOnItemClickListener(lstSubcatItemClickListener);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (SubCatFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement HoofdCatFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private ListView.OnItemClickListener lstSubcatItemClickListener = new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
//mListener.showSubCatActivity(pos+1);
}
};
}
Use FragmentActivity.
public class SubCatActivity extends FragmentActivity{
....
}
FragmentActivity
Replace or add the fragment inside onPostCreate, not on onCreate.

Categories

Resources