I am making a list that will be placed under another view.
Based on the other article, i should contain the other view in the header of the listview.
I am using ListFragment and will be attached to several activity. So I am creating a method to set the header of the ListFragment.
The problem is the getListView() method is returning null, although I call the addHeader after the list is shown.
Why is the the getListView() is always null?
Here is my code:
public class NewsListFragment extends ListFragment {
private final int topNewsCount = 5;
private DBNewsDataSource dataSource;
private Activity myActivity;
private Context myContext;
private boolean isHome;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isHome = true;
myActivity = getActivity();
Bundle extras = myActivity.getIntent().getExtras();
if (extras != null) {
isHome = extras.getBoolean("isHome");
}
dataSource = new DBNewsDataSource(getActivity());
dataSource.open();
List<DBNews> news = dataSource.getAllNews();
List<String> titleList = new ArrayList<String>();
dataSource.close();
for(int i = 0; i< (isHome?topNewsCount:news.size()); i++)
{
titleList.add(news.get(i).getTitle());
}
NewsListArrayAdapter adapter = new NewsListArrayAdapter(getActivity(),news,titleList,isHome);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something with the data
}
public void addHeader(View v)
{
ListView lv = getListView();
lv.addHeaderView(v);
}
Here is the activity that call the Fragment
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.template_activity_home);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
NewsListFragment frgNews = new NewsListFragment();
MainSlideShowFragment frgSS = new MainSlideShowFragment();
View vw = frgSS.getView();
frgNews.addHeader(vw);
fragmentTransaction.add(R.id.layout_news_list , (Fragment) frgNews);
fragmentTransaction.commit();
//frgNews.addHeader(vw);
}
Override onCreate view and let it returns a View wich contains a ListView with id android:id="#android:id/list"
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cart_list,
null);
return view;
}
You are using a fragment but haven't called
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
This is where the layout will be inflated. Hence it is null as it is not yet inflated.
Related
I have a Fragment with a ListView. When I click one of the item, a new Fragment is opened, and from this Fragment I want to open a new Fragment witha a Button.
I try to write the code, but it's a mess. When a click the Button, the program is crashed.
Should I use another way? I call the third Fragment like the second
Activity:
public class Grade extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSt
ate);
setContentView(R.layout.activity_grade);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
new Objectlist()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new Objectlist();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new Examlist();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
selectedFragment).commit();
return true;
}
};
}
1st Fragment:
public class Objectlist extends Fragment {
View v;
DB mydb;
ListView listView;
private String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Gradeview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
String jegyAtlag="0";
Cursor data = mydb.JegyekAtlaga(teszt);
while (data.moveToNext()) jegyAtlag=data.getString(0);
String jegyDarab="0";
data = mydb.JegyekDarabszama(teszt);
while (data.moveToNext()) jegyDarab=data.getString(0);
if (jegyAtlag.equals("") || jegyDarab.equals(""))
else {
bundle.putString("Tantárgy átlaga", jegyAtlag);
bundle.putString("Tantárgy darabszáma", jegyDarab);
TextView jegyekHeader = (TextView) v.findViewById(R.id.header);
jegyekHeader.setText(teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
ListView listaNezet = (ListView) v.findViewById(R.id.Gradeview);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
}
);
}
return v;
}
}
2nd Fragment:
public class targyAdatok extends Fragment {
public targyAdatok() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_targy_adatok, container, false);
Button elemzes = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.targyAdatok,jegyekAllando);
FragTan.commit();
}
});
return v;
}
}
3rd Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("Tantárgy átlaga");
String jegyDarabSt = bundle.getString("Tantárgy darabszáma");
return rootView;
}
}
I solved my problem. The problem was that a replaced the wrong fragment. Every time I have to replace the Activity's Fragment.
i am stuck at nested fragments , some one please guide me a little bit. i am in learning phase...
actually i am using a bottomNavigationView and popluate fragments and when selecting an item, one fragment has a view pager and tab layout in it, and loading list data from fire base. the problem is that when a fragment with viewpager in it selected, data fetched successfuly but not populated in list view, but when i swite view pages the listview is populated . any one please help me for this problem or guide me where to put network calls in fragment or something else solution of it.
First Fragment which have Viewpager in .
public class explore extends Fragment {
public static explore Instance = null;
private TabLayout tabLayout;
private ViewPager viewPager;
private Activity activity;
private Context context;
private PagerAdapter pagerAdapter;
public static explore getInstance() {
if (Instance == null) {
Instance = new explore();
}
return Instance;
}
public explore() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
activity = (Activity) getActivity();
context = getActivity();
return inflater.inflate(R.layout.fragment_explore, container, false);
}
#Override
public void onViewCreated(#NonNull View v, #Nullable Bundle savedInstanceState) {
tabLayout = v.findViewById(R.id.tabs_Explore);
viewPager = v.findViewById(R.id.viewpager_Explore);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
List<Category> categories = new FirebaseHelper(getActivity()).getCategoriesList();
pagerAdapter = new PagerAdapter(getChildFragmentManager(), categories);
viewPager.setAdapter(pagerAdapter);
super.onActivityCreated(savedInstanceState);
}
}
pager's first fragment means(ChildFragment)
public class categories extends Fragment {
private static categories Obj = null;
private RecyclerView listView;
private List<Category> categoryList;
private CategoryAdapter categoryAdapter;
public categories() {
categoryList = new ArrayList<>();
}
public static categories getInstance() {
if (Obj == null) {
Obj = new categories();
}
return Obj;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_blank, container, false);
listView = v.findViewById(R.id.mRecycler);
listView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
listView.setHasFixedSize(true);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(listView);
categoryAdapter = new CategoryAdapter(getActivity(), categoryList);
listView.setAdapter(categoryAdapter);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
Bundle bundle = getArguments();
if (bundle != null) {
categoryList = bundle.getParcelableArrayList("data");
categoryAdapter.notifyDataSetChanged();
}
super.onActivityCreated(savedInstanceState);
}
}
I have two Fragment,
I want to send the list view data from fragment 1 to fragment two.
when the user clicks the button on Fragment1_listview.xml the fragment2_listview will appear and it has the same data from fragment1.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
CartFragment();
FragmentManager manager = getSupportFragmentManager();
final int commit =
manager.beginTransaction().replace(R.id.fragment_container, cartFragment,
cartFragment.getTag()).commit();
}
}
Fragment1.java
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_cart, container, false);
return view;
}
#Override
public void processFinish(String s) {
try {
itemList = new JsonConverter<Cart>().toArrayList(s, Cart.class);
} catch (Exception e) {
e.printStackTrace();
}
BindDictionary dic = new BindDictionary();
dic.addStringField(R.id.tvName, new StringExtractor<Cart>() {
#Override
public String getStringValue(Cart item, int position) {
return item.orderName;
}
});
dic.addStringField(R.id.tvDesc, new StringExtractor<Cart>() {
#Override
public String getStringValue(Cart item, int position) {
return item.description;
}
}).visibilityIfNull(View.GONE);
adapter = new FunDapter<>(CartFragment.this.getActivity(), itemList,
R.layout.cart_row, dic);
lv = (ListView)view.findViewById(R.id.lvCart);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
Fragment2.java
public View onCreateView(LayoutInflater inflater, final ViewGroup
container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_payment, container, false);
return view;
}
but I don't know how to do it. please help me.
I think the best solution for you is to have the variables inside the main activity and access them from fragments. I mean, if you have to do THE SAME in all fragments, you can write the code inside the activity and just call the method you need.
I was trying to inflate a same fragment through a fragment and passing arguments, its working but the arguments which are passed are applied on the previous fragment but not on the new fragment.
The fragment contains a TextView and a Spinner.
fragment class:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.myfragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle b = getArguments();
qust = b.getString("Question","");
id = b.getInt("id");
final connection con = (connection) getActivity();
question = (TextView) getActivity().findViewById(R.id.question);
spinner = (Spinner) getActivity().findViewById(R.id.spinner);
question.setText(qust);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),id,R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (i!=0)
con.inflate();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
I am inflating a fragment when the user selects any item in the previous fragment spinner.
MainActivity class:
public class MainActivity extends AppCompatActivity implements connection {
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragments mF = new MyFragments();
Bundle b = new Bundle();
b.putString("Question","Where are you?");
b.putInt("id",R.array.planets_array);
mF.setArguments(b);
FragmentManager manage = getFragmentManager();
FragmentTransaction trans = manage.beginTransaction();
trans.add(R.id.root,mF,"frag");
trans.commit();
}
#Override
public void inflate() {
MyFragments f = new MyFragments();
Bundle b = new Bundle();
b.putString("Question","what are you doing?");
b.putInt("id",R.array.colours);
f.setArguments(b);
FragmentTransaction tran = getFragmentManager().beginTransaction();
tran.add(R.id.root,f,"added");
tran.commit();
}
}
interface to communicate b/w fragments:
public interface connection {
void inflate();
}
screenshot
I think that has been occurred, because you instantiate new fragment on
your inflate() method without unique TAG. Set up unique TAG or use different add(#IdRes int containerViewId, Fragment fragment) instead.
Hello I am using Fragment in my android application. I need to get the view which I can get using.
mNoteEditText = rootView.findViewById(R.id.noteEditText);
This mNoteEditText is require to access in onBackPressed so every view reference I need to make them static variable because of Fragment class is static. I know to make every view to static variable is not good approach. How this I can make such that I dont need to make any static variable of the view.
public class NotesActivity extends Activity {
private int bookId;
private int chapterId;
private static EditText mNoteEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
// get data from intent that sent from home activity
bookId = getIntent().getIntExtra("book_id", -1);
chapterId = getIntent().getIntExtra("book_id", -1);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new NoteFragment()).commit();
}
}
/**
* A note fragment containing a note layout.
*/
public static class NoteFragment extends Fragment {
public NoteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes,
container, false);
mNoteEditText = (EditText) rootView.findViewById(R.id.noteEditText);
return rootView;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
// get database instance
MySQLiteOpenHelper db = MySQLiteOpenHelper.getInstance(this);
Notes note = new Notes();
note.setBookId(bookId);
note.setChapterId(chapterId);
note.setNote(mNoteEditText.getText().toString());
}
}
Please help and thanks in advance.
A Fragment has a Method called getView(). With it you can get the View of the Fragment as long as it is attached to an Activity.
View view = fragment.getView();
But if you are looking for a View inside the Fragment you can also just get it with findViewById() from the Activity. Again the Fragment has to be attached to the Activity for this to work.
BUT you should not do that. Nothing outside the Fragment should have anything to do with something inside the Fragment. Write public methods in the Fragment to interact with it. Try something like this:
public static class NoteFragment extends Fragment {
private EditText noteEditText;
public NoteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
this.noteEditText = (EditText) rootView.findViewById(R.id.noteEditText);
return rootView;
}
// I added the following 3 methods to interact with the Fragment
public boolean isEmpty() {
final String text = this.noteEditText.getText().toString();
return text.isEmpty();
}
public String getText() {
return this.noteEditText.getText().toString();
}
public void setText(String text) {
this.noteEditText.setText(text);
}
}
And now in your Activity you can do this:
public class NotesActivity extends Activity {
private int bookId;
private int chapterId;
private NoteFragment noteFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
// get data from intent that sent from home activity
bookId = getIntent().getIntExtra("book_id", -1);
chapterId = getIntent().getIntExtra("book_id", -1);
if (savedInstanceState == null) {
this.noteFragment = new NoteFragment();
getFragmentManager().beginTransaction().add(R.id.container, this.noteFragment).commit();
}
// Now you can interact with the Fragment
this.noteFragment.setText("some text");
...
if(!this.noteFragment.isEmpty()) {
String note = this.noteFragment.getText();
...
}
}
}