List View in a fragment is not working? - android

I am using the following code for using a listview in a fragment. I don't know why it is not working?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
SharedPreferences allcontactssharedpreferences = getActivity().getSharedPreferences("ALL_LIST_FOR_CONTROL", Context.MODE_PRIVATE);
Map<String,?> keys = allcontactssharedpreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Toast.makeText(getActivity(),entry.getKey(),Toast.LENGTH_LONG).show();
if ( entry.getKey() != null)
AllContacts.add(entry.getKey());
}
listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
listView.setAdapter(adapter);
return view;
}
I tried the follwing solving, but it didn't work either: List View in Fragment not working
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
SharedPreferences allcontactssharedpreferences = getActivity().getSharedPreferences("ALL_LIST_FOR_CONTROL", Context.MODE_PRIVATE);
Map<String,?> keys = allcontactssharedpreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Toast.makeText(getActivity(),entry.getKey(),Toast.LENGTH_LONG).show();
if ( entry.getKey() != null)
AllContacts.add(entry.getKey());
}
// listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
//
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
//
// listView.setAdapter(adapter);
return view;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
listView.setAdapter(adapter);
}
Please help me.
Edit 1:fragment_home.xml is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.shiza.callhistorycontrol.Home">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/theListOfHistoryControl" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/theListOfHistoryControl">
</ListView>
</LinearLayout>

Related

Error on the second fragment with recycler view layout manager

I have a mainActivity with a fragment container which i set one of three fragments in it.
In each one i have a recycler view and I move to the next fragment on an item click.
The first fragment with the recyclerView is set as follows
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_courses, container, false);
mRootRef = FirebaseDatabase.getInstance().getReference();
mCoursesList = view.findViewById(R.id.courses_rv);
linearLayoutManager = new LinearLayoutManager(getContext());
mCoursesList.setLayoutManager(linearLayoutManager);
mCoursesList.setHasFixedSize(true);
updateView();
return view;
}
the error happens when entering the second fragment which is done as
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
mSubjectsList = view.findViewById(R.id.subjects_rv);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setHasFixedSize(true);
Bundle bundle = this.getArguments();
if (bundle != null) {
courseName = bundle.getString( "CourseName");
subjectName = bundle.getString( "SubjectName");
}
// Inflate the layout for this fragment
return view;
}
Apparently they are the same but with the error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
The XML files
Main2Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.crash.mathtest.Views.Main2Activity">
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
></LinearLayout>
</LinearLayout>
CoureseFragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.crash.mathtest.Views.CoursesFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/courses_rv"
/>
</FrameLayout>
Subjects fragment is the same as courses fragment
Again, this only appears on the second fragment (onCreateView)
The error points to the setLayoutManager(linearLayout)
Can't I make new layouts in the same activity ?
doesn't the new one override the last ?
You don't need to declare twice setLayoutManager() method. You are doing:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setLayoutManager(mSubjectsList.getLayoutManager());
Instead of this, just declare:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
Try to move your recyclerView data from onCreateView to onViewCreated.
Inside onCreateView() method:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_fragment, container, false);
}
Now add your recyclerView content to onViewCreated() method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.recyclerViewId);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
}
UPDATE
do this stuff in
onActivityCreated from onCreateView
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setHasFixedSize(true);
Bundle bundle = this.getArguments();
if (bundle != null) {
courseName = bundle.getString( "CourseName");
subjectName = bundle.getString( "SubjectName");
}

fragment to fragment android call

I want open fragment when I click listitem (fragment) but failed, no error logcat.
fragment_item_two.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.ItemTwoFragment"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</FrameLayout>
fragment1 (listview): (ItemTwoFragment.java)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_two, container, false);
BottomNavigationView bottomNavigationView = (BottomNavigationView)
view.findViewById(R.id.navigation);
contactList = new ArrayList<>();
lv = (ListView) view.findViewById(R.id.list);
new GetContacts().execute();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> pa, View v, int p, long id) {
int itm = (int) pa.getItemAtPosition(p);
fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragmentContainer, new NewsFragment());
transaction.commit();
}
});
return view;
}
NewsFragment:
public class NewsFragment extends Fragment {
}
fragment_news:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.NewsFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="news fragment" />
</FrameLayout>
how to fix this problem? or can you give me the reference for this case? thanks
you forget to inflate your fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
// Your code ....
return rootView;
}

ListView appears under the clicked button

I have the following implementation which runs with no hassle. When user clicks on a button then list view shows. However, list view shows up in the middle of screen. I want it to show up just beneath of the clicked button. Here is my implementation:
MainActivity
namespace DialogExample
{
[Activity (Label = "DialogExample", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
private Button mClickBtn;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
mClickBtn = FindViewById<Button> (Resource.Id.myButton);
mClickBtn.Click += MClickBtn_Click;
}
void MClickBtn_Click (object sender, EventArgs e)
{
FragmentTransaction transaction = FragmentManager.BeginTransaction ();
Dialog_Form dialogList = new Dialog_Form ();
dialogList.Show (transaction, "Dialog fragment");
}
}
}
Diaolog_Form
namespace DialogExample
{
public class Dialog_Form:DialogFragment
{
private ListView myListView;
private List<string> myList=new List<string> ();
public Dialog_Form ()
{
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
myList.Add ("Jason");
myList.Add ("Kenny");
myList.Add ("Tedd");
var view = inflater.Inflate (Resource.Layout.dialog_form, container, false);
myListView = view.FindViewById<ListView> (Resource.Id.myListView);
ArrayAdapter adapter = new ArrayAdapter (Activity, Android.Resource.Layout.SimpleListItem1, myList);
myListView.Adapter = adapter;
return view;
}
public override void OnActivityCreated (Bundle savedInstanceState)
{
Dialog.Window.RequestFeature (WindowFeatures.NoTitle);
base.OnActivityCreated (savedInstanceState);
}
}
}
Main.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/myButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Here" />
</LinearLayout>
dialog_form.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px">
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/myListView" />
<Button
android:text="Project Download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/downloadButton" />
</LinearLayout>
This should work:
public class Dialog_Form:DialogFragment
{
private ListView myListView;
private List<string> myList=new List<string> ();
public Dialog_Form ()
{
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
myList.Add ("Jason");
myList.Add ("Kenny");
myList.Add ("Tedd");
var view = inflater.Inflate (Resource.Layout.dialog_form, container, false);
myListView = view.FindViewById<ListView> (Resource.Id.myListView);
ArrayAdapter adapter = new ArrayAdapter (Activity, Android.Resource.Layout.SimpleListItem1, myList);
myListView.Adapter = adapter;
// Dialog.Window.SetGravity (GravityFlags.CenterHorizontal | GravityFlags.Top);
var layoutParam = Dialog.Window.Attributes;
layoutParam.Width = ViewGroup.LayoutParams.MatchParent;
layoutParam.X = 80;
layoutParam.Y = 200;
Dialog.Window.Attributes = layoutParam;
return view;
}
public override void OnActivityCreated (Bundle savedInstanceState)
{
Dialog.Window.RequestFeature (WindowFeatures.NoTitle);
base.OnActivityCreated (savedInstanceState);
}
}
Specify the x & y position by setting them in the oncreateview. The x & y position should be calculated by the x & y position from your button + the height & width so it will show it above the button.

Passing data from ListView to Fragment

I have a ListView in my fist screen that shows some information. When I click on each item, I have another listView with new information and textview in the same page, I want to show the pervious list view row in text view,
would you please let me know how can I implement this,
Thanks in advance!
here is my xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="######">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:visibility="gone"
android:text="test" />
<TextView
android:id="#+id/list_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:text="#string/no_message"
android:textColor="#000000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:gravity="center"></TextView>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
</LinearLayout>
Here is my java file that shows the listview and
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
listView = (ListView)view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getActivity().getActionBar().setTitle(R.string.title_forms);
TextView details = (TextView)view.findViewById(R.id.detail_header);
details.setVisibility(View.VISIBLE);
return view;
}
Here is one of my fragment that has onItemClick Listener
public class ListFragment extends Fragment implements AdapterView.OnItemClickListener {
public static final String TAG = "ListFragment";
private ListView listView;
private ArrayList<String> testIds;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
tripIds = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
registerForContextMenu(listView);
return view;
}
Here is my onItemClick :
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
chooseTest(testIds.get(position));
String selectedTestId = testIds.get(position);
Helpers.saveToSharedPreferences(getActivity(),
Constants_Prefs.SELECTED_TOP_LEVEL_RECORD,
Constants_Keys.SELECTED_TEST_ID,
selectedTestId);
I don't know how can I get that information
FormTypeListFragment passDataTo = new FormTypeListFragment();
Bundle bundle = new Bundle();
bundle.putString("DATA", selectedTestId);
passDataTo.setArguments(bundle);
}
Before launching your fragment to display selected item use setArguments() method to add key value pair of string in your case, Then in your fragment on createView use fragments method getArguments() to retain your passed string
Pass the value in bundle as :
Set :
YourFragment fragmnt = new YourFragment ();
Bundle bundle = new Bundle();
bundle.putString("item","name");
fragmnt.setArgument(bundle);
Get :
Then in your Fragment, retrieve the data (e.g. in onCreate()) with:
Bundle bundle = this.getArguments();
String myValue = bundle.getInt("item", "");

Android + ListFragment with a custom view hierarchy

I'm attempting to customize the fragment layout by returning my own view hierarchy from onCreateView(LayoutInflater, ViewGroup, Bundle). This inflates my custom view, but seems to stack the views instead of inflating within, I see everything at once. Any help is appreciated.
MyActivity.java:
public class MyActivity extends FragmentActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
ArrayListFragment list = new ArrayListFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class ArrayListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inflater.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.main, container);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String List[] = {"Larry", "Moe", "Curly"};
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, List));
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="THIS IS A BUTTON" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data" />
</LinearLayout>
I wasn't returning the new view within the onCreateView method of the ListFragment class. For instance:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, null);
return view;
}
All works well now in the land of Android!
I think you'd better
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.main, container, false);
return root;
}
optimized way and shot code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_alphabet, container, false);
}
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
List is not accepted, it's looking for a fragment.
use this pattern, works perfectly!
inflater.inflate(R.layout.list_layout, container, false);
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

Categories

Resources