ListView in DialogFragment does not show up - android

I want to implement a button on my MainActivity which triggers a DialogFragment where ListView inside. When I click on the button in my MainActivity, DialogFragment does not show up. The development environment is Xamarin.Android. 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;
}
}
}

Related

Open a fragment from a fragment's fragment?

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.

How to transfer the value to recylerview of one which is received from another fragment?

i have made two fragments in my app.
1st fragment (EditFrag) and 2nd fragment (ListTable). i want to transfer the value of 1st fragment(from EditText of 1st fragment) to the recyclerView of 2nd fragment.
how should i do that.....i can't find right documentation.
Thank you for your concern!
MainActivity:
public class MainActivity extends AppCompatActivity implements EditFrag.TransferValue{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListTable frag1=new ListTable();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.table_value_container,frag1,"fragment");
transaction.commit();
EditFrag frag2=new EditFrag();
FragmentManager manager1=getSupportFragmentManager();
FragmentTransaction transaction1=manager1.beginTransaction();
transaction1.add(R.id.table_container,frag2,"fragment_edit");
transaction1.commit();
}
#Override
public void sendValue(String value) {
Log.d("ashu","button is pressed");
ListTable listTable = (ListTable) getSupportFragmentManager().findFragmentById(R.id.table_value_container);
listTable.receiveValue(value);
}
}
2nd fragment(ListTable):
public class ListTable extends Fragment {
public TextView myEditText1;
private RecyclerView recyclerView;
public ListTable() {
// Required empty public constructor
}
public static ListTable newInstance(String param1, String param2) {
ListTable fragment = new ListTable();
Bundle args = new Bundle();
Log.d("ashu", "new instance is called :");
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ashu", "oncreata called by inflating: ");
View view = inflater.inflate(R.layout.fragment_list_table, container, false);
myEditText1 = (TextView) container.findViewById(R.id.table_value);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
MyAdapter a = new MyAdapter();
recyclerView.setAdapter(a);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void receiveValue(String value) {
myEditText1.setText(value);
}
public class MyAdapter extends RecyclerView.Adapter<MyDataViewHolder> {
#Override
public MyDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("ashu", "oncreateview holder of adapter ia called");
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_list_table, parent, false);
return new MyDataViewHolder(view);
}
#Override
public void onBindViewHolder(MyDataViewHolder holder, int position) {
holder.myEditText.setText("Table: " + position);
}
#Override
public int getItemCount() {
return 10;
}
}
public class MyDataViewHolder extends RecyclerView.ViewHolder {
public TextView myEditText;
public MyDataViewHolder(View itemView) {
super(itemView);
Log.d("ashu", "DAta view holder is called: ");
myEditText = (TextView) itemView.findViewById(R.id.table_value);
}
}
}
1st Fragment(EditFrag):
public class EditFrag extends Fragment {
TransferValue SendData;
EditText inputvalue;
Button click;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.edit_frag_layout, container, false);
inputvalue = (EditText) view.findViewById(R.id.edit_text);
click = (Button) view.findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String received = inputvalue.getText().toString();
SendData.sendValue(received);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SendData = (TransferValue) context;
} catch (ClassCastException e) {
Log.d("ashu", "implement the methods");
throw new ClassCastException("implemented the methods");
}
}
public interface TransferValue {
public void sendValue(String value);
}
}
create the instance of fragment2 from where want to receive the value to:
public static Fragment2 createInstance(String data) {
Fragment2 fragment = new Fragment2();
Bundle bundle = new Bundle();
bundle.putString("keyword", data);
fragment.setArguments(bundle);
return fragment;
}
and the get the data as below:
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("data");
}
You can use bundle in an order to pass data to fragment:
Example:
// Set bundle as arguments to the fragment
Bundle bundle = new Bundle();
bundle.putString(MyKey1, MyValue1);
bundle.putString(MyKey2, MyValue2);
MyFragment myFragment = new MyFragment();
myFragment.setArguments(bundle);
Inside onCreateView of fragment:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.repairer_part_details_fragment, container, false);
String value1 = getArguments().getString(MyKey1);
String value2 = getArguments().getString(MyKey2);
return view;
}
There are many ways to do that. I see your codes above, and 2 fragments loaded at the same time. I usaually use one of 2 ways below to do it.
The first solution: You can use this link using obserable pattern to communication 2 fragments.
The second solution: you can use EventBus lib for communication, it 's very simple

Display layout in fragment on main activity xamarin

I am not able to display layout on class SecondFragment : Fragment
MAIN ACTIVITY
$ [Activity (Label = "project", Theme = "#style/Tab")]
public class TabActivity : Activity
{
ProductDB dbHelper;
ICursor cursor;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.MainTab);
dbHelper = new ProductDB(this);
cursor = dbHelper.ReadableDatabase.RawQuery ("select * from movie", null);
StartManagingCursor (cursor);
this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
AddTab ("Products", new FirstFragment(this, cursor));
AddTab ("User Profile", new SecondFragment());
AddTab("User Order", new ThirdFragment());
if (savedInstanceState != null)
this.ActionBar.SelectTab(this.ActionBar.GetTabAt(savedInstanceState.GetInt("tab")));
}
void AddTab (string tabText, Fragment view)
{
var tab = this.ActionBar.NewTab ();
tab.SetText (tabText);
tab.TabSelected += delegate(object sender, ActionBar.TabEventArgs ab)
{
var fragment = this.FragmentManager.FindFragmentById(Resource.Id.frameLayout1);
if (fragment != null)
ab.FragmentTransaction.Remove(fragment);
ab.FragmentTransaction.Add (Resource.Id.frameLayout1, view); };
tab.TabUnselected += delegate(object sender, ActionBar.TabEventArgs ab) {
ab.FragmentTransaction.Remove(view); };
this.ActionBar.AddTab (tab);
}
protected override void OnDestroy ()
{
StopManagingCursor (cursor);
cursor.Close ();
base.OnDestroy ();
}
class FirstFragment: Fragment
{
ICursor cursor;
ListView listView;
Activity context;
public FirstFragment(Activity context, ICursor cursor) {
this.cursor = cursor;
this.context = context;
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
var view = inflater.Inflate (Resource.Layout.Tab1, container, false);
listView = view.FindViewById<ListView> (Resource.Id.mylist);
listView.Adapter = new ProductAdapter (context, cursor);
listView.ItemClick += OnItemListClick;
return view;
}
protected void OnItemListClick (object sender, AdapterView.ItemClickEventArgs ab)
{
var curs = (ICursor)listView.Adapter.GetItem (ab.Position);
var movieName = curs.GetString (1);
Android.Widget.Toast.MakeText (context, movieName, Android.Widget.ToastLength.Short).Show();
}
}
class SecondFragment : Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(R.layout.your_fragment, container, false);
return view;
}
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.article_view, container, false);
// base.OnCreateView(inflater, container, savedInstanceState);
// var view = inflater.Inflate(Resource.Layout.User, container, false);
// var layout = view.FindViewById<LinearLayout>(Resource.Id.linearLayoutmargin1);
// return view;
}
class ThirdFragment : Fragment
After observing above code, there might be some issue in onCreateView of SecondFragment, you missed below line,
base.OnCreateView (inflater, container, savedInstanceState);
Confirm and let me know whether working or not?
:)GlbMP

Android fragments on back exists application

I am having a problem with fragments. I want to start a fragment when I click an item from a Contacts list and then, when I press the phone back button I wanna go back to the contacts list. The fragments starts, but when I press the back button it doesn't go to the contacts lists, it just exists the application and gets to the phone menu.
This is for the contacts list
public class ChatMainActivity extends FragmentActivity{
private static Button btnLogOut;
private static SessionManager sm;
private static ListView listView ;
private List<ContactData> contactsList;
private static class ContactListFragment extends Fragment
{
public static Fragment newInstance(){
ContactListFragment ourList = new ContactListFragment();
return ourList;
}
#Override
public View onCreateView(LayoutInflater inflater,final ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.contactlistfragment,container,true);
listView = (ListView) v.findViewById(R.id.listView);
btnLogOut = (Button) v.findViewById(R.id.btnLogOut);
btnLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SessionManager sm = new SessionManager(v.getContext());
sm.logoutUser();
Intent i = new Intent(v.getContext(),MainActivity.class);
startActivity(i);
getActivity().finish();
}
});
System.out.println("fetch" + sm.fetchContacts());
List<String> nume = new ArrayList<String>();
List<ContactData> contactsList = new ArrayList<ContactData>();
for(String contact : SessionManager.getUserObj().getContactsInfo())
{
for(int i=0; i< sm.fetchContacts().size(); i=i+2){
if(sm.fetchContacts().get(i+1).equals(contact)){
contactsList.add(new ContactData(sm.fetchContacts().get(i).toString(),sm.fetchContacts().get(i+1).toString(),true));
nume.add(sm.fetchContacts().get(i));
}
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, nume);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int itemPosition = position;
// String itemValue = (String) listView.getItemAtPosition(position);
MessagingFragment cChat = new MessagingFragment();
ViewGroup parentViewGroup = (ViewGroup) view.getParent();
System.out.println("Removed Views? ");
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer,cChat).commit();
// Intent i = new Intent(view.getContext(), MessagingActivity.class);
// startActivity(i);
// Here is the tricky part
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Here we set our custom adapter. Now we have the reference to the activity
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_layout);
sm = new SessionManager(this);
if (SessionManager.getUserObj() == null){
// We are checking to see if the Singleton object is set, if it isn't we must send the user back to login screen.
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
finish();
}
ContactListFragment clist = new ContactListFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, clist).commit();
}
}
and this is the fragment
public class MessagingFragment extends Fragment {
private EditText et ;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
container.removeAllViews();
container.removeAllViewsInLayout();
View v = inflater.inflate(R.layout.messaging_screen,null,true);
et = (EditText) v.findViewById(R.id.etmessage);
v.findViewById(R.id.sendMessageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMessageHistory(et.getText().toString());
et.setText("");
}
});
System.out.println("Init1");
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
et = (EditText) view.findViewById(R.id.etmessage);
view.findViewById(R.id.sendMessageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMessageHistory(et.getText().toString());
et.setText("");
}
});
System.out.println("Init2");
}
public void updateMessageHistory(String newText){
TextView tv = (TextView) getView().findViewById(R.id.messageHistory);
String oldText = tv.getText().toString();
oldText = oldText + "\n" + newText ;
tv.setText(oldText);
}
}
Any help would be appreciated.
Back stack is not turned on for fragments by default. But you can enable it easily. Try in your Activity's onCreate() to replace:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clist)
.commit();
with
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clist)
.addToBackStack(null)
.commit();
More info on Back stack:
http://android-er.blogspot.com/2013/04/allow-navigate-back-through.html

ListFragment getListView is null

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.

Categories

Resources