communicate from dialog fragment to fragment - android

I have two fragments:AllItemsFragment, CreateItemDialogFragment
The AllItemsFragment displays a list of items in the sqlite,CreateItemDialogFragment is used to create the item to the SQLite.
Now I have a question is after I creating a item in createItemDialogFragment,the dialog dismiss, how to update the display of the items in AllItemsFragment
In AllItemsFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(LIFETAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_all_items, container, false);
ButterKnife.bind(this, view);
tvTitle.setText("All Items");
DbHandler dbHandler = new DbHandler(getActivity(),null,null,1);
ArrayList<Item> items = dbHandler.getAllItems();
AllItemsAdapter adapter = new AllItemsAdapter(getActivity(),items);
lvItems.setAdapter(adapter);
return view;
}
In CreateItemDialogFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
View view =inflater.inflate(R.layout.fragment_create_item_dialog,null);
ButterKnife.bind(this, view);
itemPrice.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
return view;
}
#OnClick(R.id.clear)
void clearDialog(){
dismiss();
}
//create item
#OnClick(R.id.save)
void saveItem() {
if(!itemName.getText().equals(null)||!itemPrice.getText().equals(null)){
String name = itemName.getText().toString();
String priceStr = itemPrice.getText().toString();
Double price = Double.parseDouble(priceStr);
Item item = new Item(name,price);
DbHandler dbHandler = new DbHandler(getActivity(),null,null,1);
dbHandler.addItems(item);
dismiss();
}
}

Try to update the data on onResume callback of the AllItemsFragment.
#Override
public void onResume(){
super.onResume();
// update data over here.
}

Related

Call a function defined in a fragment, from the main activity that required a view

I have a function in a fragment (Frag_Lista) that changes its cardView dynamically using the output of a query.
The first time i call it from that fragment and it works. The second time i would call it from the main activity, but i can't set correctly the second parameter, the view.
Frag_Lista
public void function_in_fragment() {
//some code
Context context = getActivity();
DBhelper database = ((MainActivity)getActivity()).getDatabase();
Cursor cursor=database.ottieni_tutto();
genera_lista(cursor,getView());
}
public void genera_lista(Cursor cursor, View v) {
list.clear();
if(cursor!=null) {
if(cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
//Log.d(TAG,cursor.getString(cursor.getColumnIndex(DBhelper.COL_NOME)));
String nome = cursor.getString(cursor.getColumnIndex(DBhelper.COL_NOME));
String tipo = cursor.getString(cursor.getColumnIndex(DBhelper.COL_TIPO));
String difficolta = cursor.getString(cursor.getColumnIndex(DBhelper.COL_DIFFICOLTA));
String immagine = cursor.getString(cursor.getColumnIndex(DBhelper.COL_IMMAGINE));
Food_Card food_card = new Food_Card(immagine, nome, tipo, difficolta);
list.add(food_card);
cursor.moveToNext();
}
cursor.close();
}
else Log.d(TAG,"Cursor vuoto");
}
else Log.d(TAG,"Cursor nullo");
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter=new food_adapter(getActivity(),list);
recyclerView.setAdapter(adapter);
}
MainActivity
public void function_in_mainActivity(String[] parametri) {
Cursor cursor=database.query_filtri(parametri);
Frag_Lista nothing=new Frag_Lista();
View v= ?
nothing.genera_lista(cursor,v);
}
How can i pass correctly the current view?
Frag_Lista
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_lista, container, false);
setHasOptionsMenu(true);
return(v);
}
Change your onCreateView like this
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_lista, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
setHasOptionsMenu(true);
return(v);
}
Crate a field inside your Fragment for recyclerView.
Now you always have a reference to the RecyclerView and don't need to pass it as a argument to the method.
public void genera_lista(Cursor cursor)

Maintain fragment's view state

I have seen Link1 for this issue but could understand it right. I have a fragment that loads a list. When i click the list item it opens another activity. But i press back button it loads the list again. I want it to be at the same scroll position where it was before. In above mentioned link it specifies to use flag but i haven't got the point.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
android.app.Fragment fragment = new MeFragment();
getFragmentManager().beginTransaction().replace(R.id.layout_FragmentsContainer, fragment).addToBackStack(null).commit();
}
}
public class MeFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_me, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
meLV = (ListView) getView().findViewById(R.id.lv_Inbox);
loadingListProgress = (ProgressBar) getView().findViewById(R.id.progress_LoadingList);
meList = new ArrayList<Message>();
meAdapter = new MessagesListAdapter(getActivity(), meList);
//addFooter();
meLV.setAdapter(meAdapter);
meLV.setOnItemClickListener(this);
pageCount = 0;
loadmoreProgressDialog = new ProgressDialog(getActivity());
loadmoreProgressDialog.setTitle("Please wait ...");
loadmoreProgressDialog.setMessage("Loading more ...");
loadmoreProgressDialog.setCancelable(true);
loadUserMessages();
meLV.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// TODO Auto-generated method stub
//addFooter();
loadmoreProgressDialog.show();
loadUserMessages();
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Utils.showToast_msg(getActivity(), "MessageItemClicked");
ReferralDetailFragment fragment = new ReferralDetailFragment();
getFragmentManager().beginTransaction().replace(R.id.layout_FragmentsContainer, fragment).addToBackStack(null).commit();
}
}
public class ReferralDetailFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_referraldetail,container, false);
linkToAcknowledge = (TextView) view.findViewById(R.id.lbl_Link_to_Acknowledge);
return view;
}
}
I implemented a simple solution for this in my app, basically when you press back to go to the fragment again, onCreateView() is called. Here in onCreateView() you have done all initialization, so we change
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_me, container, false);
/*
*Whatever you want to do
*
*/
return view;
}
to:
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if(view==null){
view = inflater.inflate(R.layout.fragment_me, container, false);
/*
*Whatever you want to do
*
*/
}
else{
((ViewGroup)view.getParent()).removeView(view);
}
return view;
}
Here, we move View view outside and make it a class variable. So if it is the first time the fragment is called, it is null and the initialization occurs, otherwise it goes to else black. Else block is required because onCreateView() adds whatever it returns as a child of the view's parent, so since view is already there, we remove it and onCreateView automatically adds it again.
According to our exchange in the comments, I completely deletde my answer and re-write a new one.
I copy/paste the code from one of my apps and removing the useless things and changing the names. Hope there is not too many typing mistakes, at that it is the minimum required to have it working.
When I pop back to FirstFragment from SecondFragment, the scroll position of FirstFragment is the same as when I clicked an item to load the SecondFragment.
Note that I don't extend FragmentActivity. I have an activity which loads the fragments.
Extend/modify to match your needs.
MainActivity :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
}
}
FirstFragment Class :
public class FirstFragment extends Fragment implements OnItemClickListener {
private ListView mListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.first_fragment_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (ListView) getView().findViewById(R.id.listview_first_fragment);
mListView.setAdapter(mAdapter); // depends on your adapter
mListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListView.setItemChecked(position, true);
//in case you need, set the bundle here, for example pass the position
Bundle arguments = new Bundle();
arguments.putInt("position", position);
SecondFragment secondFragment = new SecondFragment();
secondFragment.setArguments(arguments);
getFragmentManager().beginTransaction().replace(R.id.fragment_container, secondFragment).addToBackStack(null).commit();
}
}
SecondFragment Class :
public class SecondFragment extends Fragment {
private Integer mPosition;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.second_fragment_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
if (arguments == null) {
mPosition= 0;
} else {
mPosition= arguments.getInt("Position");
}
}
}
What you are trying to achieve may be done with help of savedInstanceState. i also had this kind of problem which i resolved by using add() method instead of replace() in transition.
If you can change your method or already not using add() than give it a shot.
and if add() method didn't do the trick then check the implementation of savedInstanceState.
correctly save instance state.
How to save states of fragment views.

update spinner from dialogfragment

I have a Spinner in my class TelaEntrada.java loading normally.
public class TelaEntrada extends Fragment {
public Fragment newInstance(Context context) {
TelaEntrada telaEntrada = new TelaEntrada();
return telaEntrada;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.telaentrada, container, false);
DbEntrada banco = new DbEntrada(getActivity().getApplicationContext());
List<Tipo> tipos = banco.todosTipos();
List<String> item = new ArrayList<String>();
for(Tipo tipo : tipos){
item.add(tipo.getDescricao().toString());
}
final Spinner spn_Entrada = (Spinner) root.findViewById(R.id.spnEntradaTipo);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(
this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, item);
spn_Entrada.setAdapter(adapter2);
I too have one DialogFragment in another class. Code is below.
public class DialogTipo extends DialogFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
final View root = (View) inflater.inflate(R.layout.dialog_tipo, container, false);
final EditText txtDialogTipo = (EditText)root.findViewById(R.id.txtDialogTipo);
Button btnDialogTipoAdd = (Button) root.findViewById(R.id.btnDialogTipoAdd);
Button btnDialogTipoCancel = (Button) root.findViewById(R.id.btnDialogTipoCancel);
btnDialogTipoAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DbEntrada banco = new DbEntrada(getActivity().getApplicationContext());
banco.insereTipo(txtDialogTipo.getText().toString());
//I want update my spinner here!
dismiss();
}
});
getDialog().setTitle("Inserir Novo Tipo");
return root;
}
}
I wanted to add a new item, the spinner was directly updated the database to display the new information in the User spinner. Thanks. Sorry for my english!

How to get an id of a View inside a Fragment

Hi I am trying to get an id of some View in a Fragment from a string, however it doesn't seem to work... Is there a special case for fragments?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View singleplayerView = inflater.inflate(R.layout.singleplayer_tab, container, false);
setupMap();
return singleplayerView;
}
private void setupRank() {
TextView view = (TextView) getByStringId("rank0");
view.setText("hello");
}
private final View getByStringId(final String id) {
return findViewById(getResources().getIdentifier(id, "id", getActivi
ty().getPackageName()));
}
So I am trying to set the textView field rank0 in the layout that is used for my fragment... but right now it gets a NUllPointer because it couldnt find the id
Thank you
you can define your Layout In your onCreateView() inside Fragments like this:
View V = new View(getActivity());
V = inflater.inflate(R.layout.fragment_layout,container, false);
Then
TextView SomeField = (TextView)V.findViewById(R.id.TxtSomeField);
Inside fragment, add getActivity before findViewById:
getActivity().findViewById(...);
Try this,
String id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extra = getArguments();
id = extra.getString("id", "");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar_details, container, false);
Button b = (Button) view.findViewById(id);
return view;
}

add a header to fragmentlist android

I'm adding a header to my ListFragment but header doesn't appear. I tried add in onCreate and onStart but I already set my adapter. I found here this Best place to addHeaderView in ListFragment but it is not valid.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.header,
null);
container.addView(v,0);
rla = new RowListAdapter(getActivity().getLayoutInflater(),
R.layout.itemlayout, rl);
setListAdapter(rla);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
getListView().setBackgroundResource(R.color.tostadoclaro);
getListView()
.setDivider(getResources().getDrawable(R.drawable.divider));
getListView().setDividerHeight(4);
}
¡¡¡SOLUTION!!!
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.header,
null);
this.getListView().addHeaderView(v);
rla = new RowListAdapter(getActivity().getLayoutInflater(),
R.layout.itemlayout, rl);
setListAdapter(rla);
super.onActivityCreated(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){// Empty. Use original.}
Don't add the view to the container. Use addHeaderView(v).
The complete code (adapted from here):
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView tv = new TextView(getActivity());
tv.setText("Hello");
getListView().addHeaderView(tv);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,
new String[] { "Hello world" }));
}
#Override
public void onDestroyView() {
setListAdapter(null);
super.onDestroyView();
}
See also: Best place to addHeaderView in ListFragment

Categories

Resources