How to read object which is used by a fragment - android

First of all, I hope my question is clear. If it isn't please comment i will try to make it better!.
i have a question related to putting a item in a arraylist. I am using the master/detail flow (a standard project option in android studio) as a bases for my app. I already modified it but below is de code from the original template to simplify my question. For my problem i think there are three activities involved. Main activity, detail activity, mysavedbooks and the fragment activity.
My Problem
In the detail activity there is a fab button. WHat i want to do is to save the current displayed item in a new arraylist called Saveditems in the activity mysavedbooks.
How can i read the item (which is currently displayed by the detailactivity which extends the fragment) and put this in a saveditems arraylist.
Greetings,
Matthijs
below is the main activity
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import matthijs.bookshelf.dummy.DummyContent;
import java.util.List;
/**
* An activity representing a list of books. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {#link bookDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class bookListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
View recyclerView = findViewById(R.id.book_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.book_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.book_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, bookDetailActivity.class);
intent.putExtra(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
below is the detail activity.
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
/**
* An activity representing a single book detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link bookListActivity}.
*/
public class bookDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "saved book", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(bookDetailFragment.ARG_ITEM_ID));
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.book_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, bookListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
below is the fragment
package matthijs.bookshelf;
import android.app.Activity;
import android.support.design.widget.CollapsingToolbarLayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import matthijs.bookshelf.dummy.DummyContent;
/**
* A fragment representing a single book detail screen.
* This fragment is either contained in a {#link bookListActivity}
* in two-pane mode (on tablets) or a {#link bookDetailActivity}
* on handsets.
*/
public class bookDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
/**
* The dummy content this fragment is presenting.
*/
private DummyContent.DummyItem mItem;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public bookDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
Activity activity = this.getActivity();
CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
if (appBarLayout != null) {
appBarLayout.setTitle(mItem.content);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.book_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
((TextView) rootView.findViewById(R.id.book_detail)).setText(mItem.details);
}
return rootView;
}
}
Mysavedbooks activity
package matthijs.tuinierv2;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Matthijs on 12-2-2016.
*/
public class Mysavedbooks {
public static final List<DummyContent.DummyItem> SavedItems= new ArrayList<DummyContent.DummyItem>();
}

I kind of solved to problem for now, except for the twopane mode. I need to look in the solution for the twopane mode further. I think it can be done in a better way but here is the solution.
Please comment if you have a better solution.
I added the String in ItemDetailActivity
public static String SAVED_ITEM_ID;
In the bookListActivity i added a line of code in this part:
` #Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, bookDetailActivity.class);
intent.putExtra(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
//THE line of code I ADDED
itemDetailActivity.SAVED_ITEM_ID = holder.mItem.id;
context.startActivity(intent);
}
}
});
}`
Here is the code i added in the bookDetailActivity to retrieve the current book which is displayed in the itemdetailactivity en thereby the fragment.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabdetail);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//code i added to retrieve the current item and save it in
int SAVED_ITEM_ID_INT = Integer.parseInt(SAVED_ITEM_ID);
ItemListActivity.PlantItem SAVED_ITEM = ItemListActivity.ITEMS.get(SAVED_ITEM_ID_INT);
Mysavedbooks.SavedItems.add(SAVED_ITEM);
Snackbar.make(view,"Book saved to My books", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});

Related

How to open a Fragment on click from a fragment in Android

Firstly I'm new to android and sorry for my english.
I have an application where I display images, in it I use a grid with image gallery.
Now I need to make a gallery of images with Gif, so I found this project. LINK
My project uses Fragmets I am trying to convert this project above in mine, however I am having problems in the call Activity.
The initial project activity looks like this:
package com.tenor.android.demo.search.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.tenor.android.core.constant.StringConstant;
import com.tenor.android.core.model.impl.Tag;
import com.tenor.android.core.response.BaseError;
import com.tenor.android.core.util.AbstractUIUtils;
import com.tenor.android.core.widget.adapter.AbstractRVItem;
import com.tenor.android.demo.search.R;
import com.tenor.android.demo.search.adapter.TagsAdapter;
import com.tenor.android.demo.search.adapter.decorations.MainTagsItemDecoration;
import com.tenor.android.demo.search.adapter.rvitem.TagRVItem;
import com.tenor.android.demo.search.adapter.view.IMainView;
import com.tenor.android.demo.search.presenter.IMainPresenter;
import com.tenor.android.demo.search.presenter.impl.MainPresenter;
import com.tenor.android.demo.search.widget.TenorStaggeredGridLayoutManager;
import java.util.ArrayList;
import java.util.List;
/**
* For the MainActivity, we will display a search bar followed by a stream of Tags pulled from the Tenor API.
* Either by clicking on a tag or entering a search, SearchActivity will open.
*/
public class MainActivity extends AppCompatActivity implements IMainView{
// Number of columns for the RecyclerView
private static final int STAGGERED_GRID_LAYOUT_COLUMN_NUMBER = 2;
// Minimum length a search term can be
private static final int TEXT_QUERY_MIN_LENGTH = 2;
// A search box for entering a search term
public EditText mEditText;
// RecyclerView to display the stream of Tags
public RecyclerView mRecyclerView;
// Api calls for MainActivity performed here
private IMainPresenter mPresenter;
// Adapter containing the tag items/view holders
private TagsAdapter mTagsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.am_et_search);
mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
final String query = textView.getText().toString().trim();
if (query.length() < TEXT_QUERY_MIN_LENGTH) {
Toast.makeText(MainActivity.this, getString(R.string.search_error), Toast.LENGTH_LONG).show();
return true;
}
// The keyboard enter will perform the search
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
startSearch(query);
return true;
}
return false;
}
});
mRecyclerView = (RecyclerView) findViewById(R.id.am_rv_tags);
mRecyclerView.addItemDecoration(new MainTagsItemDecoration(getContext(), AbstractUIUtils.dpToPx(this, 2)));
// Two column, vertical display
final TenorStaggeredGridLayoutManager layoutManager = new TenorStaggeredGridLayoutManager(STAGGERED_GRID_LAYOUT_COLUMN_NUMBER,
StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mTagsAdapter = new TagsAdapter<>(this);
mRecyclerView.setAdapter(mTagsAdapter);
mPresenter = new MainPresenter(this);
mPresenter.getTags(getContext(), null);
}
private void startSearch(#Nullable final CharSequence text) {
final String query = !TextUtils.isEmpty(text) ? text.toString().trim() : StringConstant.EMPTY;
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra(SearchActivity.KEY_QUERY, query);
startActivity(intent);
}
#Override
public Context getContext() {
return getBaseContext();
}
#Override
public void onReceiveReactionsSucceeded(List<Tag> tags) {
// Map the tags into a list of TagRVItem for the mTagsAdapter
List<AbstractRVItem> list = new ArrayList<>();
for (Tag tag : tags) {
list.add(new TagRVItem(TagsAdapter.TYPE_REACTION_ITEM, tag));
}
mTagsAdapter.insert(list, false);
}
#Override
public void onReceiveReactionsFailed(BaseError error) {
// For now, we will just display nothing if the tags fail to return
}
}
Here my first change:
Note that I changed the class name to not conflict with my MainActivity
public class MainActivityGif extends Fragment implements IMainView {
And here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setContentView(R.layout.activity_main_gif);
View view = inflater.inflate(R.layout.activity_main_gif, container, false);
How can I call a fragment within another fragment?
private void startSearch(#Nullable final CharSequence text) {
final String query = !TextUtils.isEmpty(text) ? text.toString().trim() : StringConstant.EMPTY;
Intent intent = new Intent(getActivity(), SearchActivity.class);
intent.putExtra(SearchActivity.KEY_QUERY, query);
MainActivityGif.this.startActivity(intent);
}
If I miss the way to ask, I'm sorry, let me understand where I went wrong.
private FragmentManager mFragmentManager;
private FragmentTransaction mFragmentTransaction;
and inside your onCreate
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
and on click call :
FragmentB fragment = new FragmentB ();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.contentFragment, fragment );
mFragmentTransaction.commit();

How to create fragment interaction?

These are the imports I have for the fragment class.
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
Class being initialized
public class FragmentDemo extends Fragment {
Public constructor is empty and must stay that way
public FragmentDemo() {
}
It must be attached to an activity, the interface depends on said activity
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Inflating layout for fragment
View result = inflater.inflate(R.layout.fragment_fragment_demo, container, false);
TextView textView = (TextView)result.findViewById(R.id.textView2);
Button button = (Button)result.findViewById(R.id.button2);
textView.setText("HEY, THIS IS A TEST!");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.e("FRAGMENT", "BUTTON IS WORKING!");
// why no toast?
}
});
return result;
}
}
You must create two classes to make it more clear, one for the interaction of fragments, and a main class.
The first one should look like this:
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link InteractionFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link InteractionFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class InteractionFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_NAME = "name";
private static final String ARG_LAST_NAME = "lastName";
// TODO: Rename and change types of parameters
private String name;
private String lastName;
private OnFragmentInteractionListener mListener;
public InteractionFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment InteractionFragment.
*/
// TODO: Rename and change types and number of parameters
// Factory method
public static InteractionFragment newInstance(String param1, String param2) {
InteractionFragment fragment = new InteractionFragment();
Bundle args = new Bundle();
args.putString(ARG_NAME, param1);
args.putString(ARG_LAST_NAME, param2);
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
name = getArguments().getString(ARG_NAME);
lastName = getArguments().getString(ARG_LAST_NAME);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_interaction, container, false);
TextView nameText = (TextView)v.findViewById(R.id.name);
TextView lastNameText = (TextView)v.findViewById(R.id.last_name);
nameText.setText(name);
lastNameText.setText(lastName);
Button button = (Button)v.findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.somethingHappened("THE BUTTON WAS PRESSED, HOW EXCITING!");
}
});
return v;
}
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public void onDetach() {
super.onDetach();
mListener = null;
}
public void printALog(){
Log.wtf("PRINTING", "ITS WORKING!");
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void somethingHappened(String message);
}
}
While the second one should look like this:
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.TransactionTooLargeException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements InteractionFragment.OnFragmentInteractionListener {
InteractionFragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void addFragment(Fragment f){
// add a fragment through code
// fragment manager - the guy in charge of any fragment related logic
FragmentManager manager = getFragmentManager();
// transactions
FragmentTransaction transaction = manager.beginTransaction();
// actually do the thing
//fragment = InteractionFragment.newInstance("Juan","Perez");
// 3rd parameter - fragment
transaction.add(R.id.container, f, "dude");
transaction.commit();
}
#Override
public void somethingHappened(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public void doSomethingOnFragment(View v){
fragment.printALog();
}
public void swapFragments(View v){
FragmentManager manager = getFragmentManager();
Fragment f = manager.findFragmentByTag("dude");
if(f != null){
Toast.makeText(this, "FRAGMENT BEING REMOVED", Toast.LENGTH_SHORT).show();
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(f);
transaction.commit();
} else {
Toast.makeText(this, "NO FRAGMENT TO REMOVE", Toast.LENGTH_SHORT).show();
}
}
public void addFragment1(View v){
fragment = InteractionFragment.newInstance("Juan","Perez");
addFragment(fragment);
}
public void addFragment2(View v){
FragmentDemo fd = new FragmentDemo();
addFragment(fd);
}
}
I'm not sure to understand what is your question exactly, so I will assume first that your problem is related to your "Why no toast?" comment.
The thing is you are using the log function, this prints in logcat console, not through toasts.
If you want to display a toast, use
Toast.makeText(context, text, durationInMs).show();
More info here
I'm not sure to understand what is your question exactly, so I will assume first that your problem is related to your "Why no toast?" comment.
The thing is you are using the log function, this prints in logcat console, not through toasts.
If you want to display a toast, use
Toast.makeText(context, text, durationInMs).show();
And because you are in a Fragment the Context used is the activity which has this fragment so to get context we use getActivity(). Hence the Toast will be:
Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();

Passing a data from Dialog to Fragment in android

I'm currently working in my own project of dental application, i would like to ask if how to pass a certain data from a custom dialog and show or add it to the target fragment?
Appreciate for any help.
This is the Custom Dialog Screenshot:
CustomDialog.java
package com.bloxofcode.multipletabs;
import android.app.Activity;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.bloxofcode.multipletabs.Tab1;
public class CustomDialog extends Dialog implements
View.OnClickListener {
public Activity c;
public CustomDialog d;
public Button yes, no;
ToggleButton btnGenderMale,btnGenderFemale;
Button btnCancel, btnAccept;
EditText eText;
public CustomDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setBackgroundDrawableResource(android.R.drawable.dialog_holo_light_frame);
}
else{
getWindow().setBackgroundDrawableResource(android.R.drawable.alert_light_frame);
}
setContentView(R.layout.activity_dialog);
btnGenderFemale = (ToggleButton) findViewById(R.id.toggleButtonFemale);
btnGenderMale = (ToggleButton) findViewById(R.id.toggleButtonMale);
btnCancel = (Button) findViewById(R.id.btnCancel);
btnAccept = (Button) findViewById(R.id.btnAccept);
eText = (EditText) findViewById(R.id.editText);
btnGenderMale.setChecked(true);
btnGenderMale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonMale, boolean b) {
// Toast.makeText(getApplicationContext(),
// String.valueOf(buttonMale.isChecked()), Toast.LENGTH_SHORT).show();
if(buttonMale.isChecked()){
btnGenderMale.setEnabled(false);
btnGenderFemale.setEnabled(true);
btnGenderFemale.setChecked(false);
}else{
}
}
});
btnGenderFemale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonFemale, boolean b) {
// Toast.makeText(getApplicationContext(),
// String.valueOf(buttonFemale.isChecked()), Toast.LENGTH_SHORT).show();
if(buttonFemale.isChecked()){
btnGenderMale.setEnabled(true);
btnGenderFemale.setEnabled(false);
btnGenderMale.setChecked(false);
}else{
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),"Sample",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View v) {
dismiss();
}
}
How to achieve this Expected Result:
Tab1.java
package com.bloxofcode.multipletabs;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import com.bloxofcode.multipletabs.database.DBOpenHelper;
import com.bloxofcode.multipletabs.database.NotesProvider;
/**
* A simple {#link Fragment} subclass.
*/
public class Tab1 extends Fragment {
private ImageButton imgButton;
private CustomDialog customDialog;
View v;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v =inflater.inflate(R.layout.tab_1,container,false);
imgButton = (ImageButton) v.findViewById(R.id.imageButton);
//Creating ImageButton
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getActivity(),"Hello Image Button!",Toast.LENGTH_LONG).show();
customDialog = new CustomDialog(getActivity());
customDialog.show();
}
});
press();
return v;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void press() {
insertNote("Juan Dela Cruz");
Cursor cursor = getActivity().getContentResolver().query(NotesProvider.CONTENT_URI,
DBOpenHelper.ALL_COLUMNS, null, null, null, null);
String[] from = {DBOpenHelper.NOTE_TEXT};
int[] to = {android.R.id.text1};
CursorAdapter cursorAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1,cursor,from,to,0);
ListView list = (ListView) v.findViewById(android.R.id.list);
list.setAdapter(cursorAdapter);
}
private void insertNote(String noteText) {
ContentValues values = new ContentValues();
values.put(DBOpenHelper.NOTE_TEXT,noteText);
Uri noteUri =getActivity().getContentResolver().insert(NotesProvider.CONTENT_URI,values);
Log.d("MainActivity","Inserted note " + noteUri.getLastPathSegment());
}
}
ViewPagerAdapter.java
package com.bloxofcode.multipletabs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter extends FragmentStatePagerAdapter{
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
}
else if(position == 1)
{
Tab2 tab2 = new Tab2();
return tab2;
}
else // As we are having 3 tabs if the position is now 0 it must be 1 so we are returning second tab
{
Tab3 tab3 = new Tab3();
return tab3;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
TabsActivity.java
package com.bloxofcode.multipletabs;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class TabsActivity extends AppCompatActivity {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Patient","Appointment","Backup"};
int Numboftabs =3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
//return ContextCompat.getColor(TabsActivity.this,R.color.tabsScrollColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getResources().getColor(R.color.tabsScrollColor,TabsActivity.this.getTheme());
}else {
return getResources().getColor(R.color.tabsScrollColor);
}
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#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);
}
}
If you'd like to keep things loosely coupled and structured, A fine rather alternative is to choose the EventBus . To see the usage see this Answer.
You can accomplish it using Interface.
YourInterface.java
public interface YourInterface{
void yourMethod(int data);
}
Use that Interface in your Dialog class:
public class CustomDialog extends Dialog implements
View.OnClickListener {
private YourInterface delegate;
....
public CustomDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
delegate = (YourInterface) a;
}
}
In your Activity that holds fragment implement interface:
public class YourActivity extends AppCompatActivity implements YourInterface {
....
#Override
public void yourMethod(int data) {
fragment.receiverMethod(data);
}
}
Tab1.java
public class Tab1 extends Fragment {
public void receiverMethod(int data) {
// do what you want with received data
}
}
Now to use that simply call delegate.yourMethod(data) to pass it to fragment
You can use Broadcast Receiver in your onDismiss like below in your Dialog
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (onDismissListener != null) {
Intent intent = new Intent("DialogDismiss");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
onDismissListener.onDismiss(dialog);
}
}
and in your Fragment you can receive the broadcast
// In your Fragment do below
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Work Here
}
};
//In OnCreate
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver,
new IntentFilter("DialogDismiss"));
//onDestroy
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
If you get the view from the customDialog you can just access the fields normally with view.findViewById() from in your fragment class.
Put your data into budle as key-value pair and set bundle as an argument to fragment.
fragment.setArgument(bundle)
To get bundle in fragmen, call
Bundle bundle = getArgument() and get values from the bundle based on key.
You could return the String which was entered into the EditText by creating a setter and getter method within your Dialog class to return a String variable (e.g. editTextString) which you would assign a value to whenever the accept button is clicked.
Add your getter and setter methods to the Dialog class
private void setEditTextString() {
editTextString = eText.getText().toString()
}
public String getEditTextString() {
return editTextString;
}
Within your click listener for the accept button add the following line of code:
setEditTextString(eText.getText().toString());
Then all you need to do to return the value entered in the editText field in the Fragment class would be to call the public method within your Dialog class to return the string.
dialogClass.getEditTextValue()

in viewPager's fragment, recyclerView adapter notifyDataSetChanged not works on first time

I have fragment view pager in activity, that creates a number of pages of entered number before. In each fragment, i have recycler view that needs to update each time user moves to the relevant page. on resume() of each fragment I have getter of data from main activity.
What I am experiencing is while I'm going to next page first time it's not updated, but if after some page movements I would back to it, it is updated, with same resume() code.
I tried some delays after updating the data, it didn't help.
So if before updating data I would check every page it would work as I planned, but if the page was not created before (due to pager adapter) but I still use the same code for updating, it does not work.
I would be glad for some help, stacked on it for 2 days already.
Main Activity:
package com.slavafleer.tipcalculator02;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.slavafleer.tipcalculator02.recycler.PageHeaderAdapter;
import java.util.ArrayList;
public class ManualModeActivity extends AppCompatActivity implements
PageHeaderAdapter.Callbacks, DinerFragment.Callbacks {
private int mDinersAmount;
private ViewPager mViewPagerDiners;
private PageHeaderAdapter mHeaderAdapter;
private DinersPagerAdapter mDinersPagerAdapter;
private ArrayList<Order> mOrders;
public ArrayList<Order> getOrders() {
return mOrders;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_mode);
mOrders = new ArrayList<>();
// Get diners amount from previous activity
Intent intent = getIntent();
mDinersAmount = intent.getIntExtra(Constants.KEY_DINNERS_AMOUNT, 1);
// Initialise PageHeader Recycler
mHeaderAdapter = new PageHeaderAdapter(this, mDinersAmount, this);
final RecyclerView recyclerPageHeader = (RecyclerView) findViewById(R.id.recyclerViewPagerHeader);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerPageHeader.setLayoutManager(linearLayoutManager);
recyclerPageHeader.setAdapter(mHeaderAdapter);
// Initialise ViewPager
mViewPagerDiners = (ViewPager) findViewById(R.id.viewPagerDiners);
FragmentManager fragmentManager = getSupportFragmentManager();
mDinersPagerAdapter = new DinersPagerAdapter(fragmentManager, mDinersAmount);
mViewPagerDiners.setAdapter(mDinersPagerAdapter);
// ViewPager Listener - synchronise with headers recycler
mViewPagerDiners.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
// Gets position for selected page
#Override
public void onPageSelected(int position) {
mHeaderAdapter.selectItem(position);
linearLayoutManager.smoothScrollToPosition(recyclerPageHeader, null,position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
// HeaderPage Adapter Callbacks
// Scroll ViewPager by clicked Header
#Override
public void onItemClick(int position) {
mViewPagerDiners.setCurrentItem(position, true);
}
// DinerFragment.OrderDialog.Callbacks
// Send data to PagerAdapter that would sent to each fragment
#Override
public void onDialogAddClick(Order order) {
Log.d("test", "onDialogAddClick");
mOrders.add(order);
mDinersPagerAdapter.updateOrders();
}
}
PagerAdapter
package com.slavafleer.tipcalculator02;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* PagerAdapter for ManualModeActivity ViewPager
*/
public class DinersPagerAdapter extends FragmentPagerAdapter {
private int mDinersAmount;
private ArrayList<DinerFragment> mDinerFragments;
public DinersPagerAdapter(FragmentManager fm, int dinersAmount) {
super(fm);
mDinersAmount = dinersAmount;
mDinerFragments = new ArrayList<>();
}
#Override
public Fragment getItem(int position) {
// Insert diners amount to fragment
Bundle bundle = new Bundle();
bundle.putInt(Constants.KEY_DINNERS_AMOUNT, mDinersAmount);
bundle.putInt(Constants.KEY_CURRENT_PAGE, position);
DinerFragment dinerFragment = new DinerFragment();
dinerFragment.setArguments(bundle);
mDinerFragments.add(dinerFragment); // save fragments references
return dinerFragment;
}
// Diners amount + All
#Override
public int getCount() {
return mDinersAmount + 1;
}
// Update order list in each fragment of view pager
public void updateOrders() {
for(DinerFragment dinerFragment : mDinerFragments) {
dinerFragment.onResume();
}
}
}
Fragment
package com.slavafleer.tipcalculator02;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.slavafleer.tipcalculator02.recycler.OrdersAdapter;
import java.util.ArrayList;
/**
* Diner Fragment Class
*/
public class DinerFragment extends Fragment implements OrderDialog.Callbacks {
private ArrayList<Order> mOrders = new ArrayList<>();
private RecyclerView mRecyclerViewOrders;
private ImageView mImageViewAddOrderButton;
private int mDinersAmount;
private OrdersAdapter mOrdersAdapter;
private int mDinerId;
private Callbacks mCallbacks;
public DinerFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("test", "onCreateView");
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_diner, container, false);
mCallbacks = (Callbacks) inflater.getContext();
// Get Diners Amount
final Bundle bundle = getArguments();
if(bundle != null) {
mDinersAmount = bundle.getInt(Constants.KEY_DINNERS_AMOUNT);
mDinerId = bundle.getInt(Constants.KEY_CURRENT_PAGE);
Log.d("test", "onCreateView " + mDinerId);
}
mRecyclerViewOrders = (RecyclerView) view.findViewById(R.id.recyclerViewOrders);
mOrdersAdapter = new OrdersAdapter(getActivity(), mOrders);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerViewOrders.setLayoutManager(linearLayoutManager);
mRecyclerViewOrders.setAdapter(mOrdersAdapter);
// Due to the bug, we could use just listener and not OnClick in Fragment
mImageViewAddOrderButton = (ImageView) view.findViewById(R.id.imageViewAddButton);
mImageViewAddOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Integer> currentPage = new ArrayList<>();
currentPage.add(mDinerId);
OrderDialog orderDialog = new OrderDialog(getActivity(),
mDinersAmount, currentPage, DinerFragment.this);
orderDialog.show();
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
Log.d("test", "onResume " + mDinerId);
ManualModeActivity activity = (ManualModeActivity) getActivity();
mOrders = activity.getOrders();
for(Order order : mOrders) {
Log.d("test", order.getPrice() + "");
}
int size = mOrders.size();
mOrdersAdapter.notifyDataSetChanged();
mRecyclerViewOrders.smoothScrollToPosition(size);
}
// Blank OrderDialog.Callbacks
// used due to Implements for creation OrderDialog
#Override
public void onDialogAddClick(Order order) {
mCallbacks.onDialogAddClick(order);
}
public interface Callbacks {
void onDialogAddClick(Order order);
}
}
Instead of using onResume use the onPageSelected method and used the passed fragment for context to call the updating method in the fragment.
Finally what I did is replacing mOrdersAdapter.notifyDataSetChanged() on recreating the adapter. I understand that is not a very smart solution but visually it does work as I needed.
I would not mark it as answer cause I still want to know why it acts like I wrote before.
Thanks again.
// mOrdersAdapter.notifyDataSetChanged();
mOrdersAdapter = new OrdersAdapter(getActivity(), mOrders);
mRecyclerViewOrders.setAdapter(mOrdersAdapter);
ViewPager adapter creates 2 fragments at the same time. for instance when you're on page 0, it also creates page 1(lifecycle for page 1: OnCreate->OnCreateView->OnResume->OnPause->OnResume).When you swipe to page 1 only method that is being called is SetMenuVisibility. So in order to update data for page 1 is to call setMenuVisibilty inside of Fragment:
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if(menuVisible && isResumed()){
settingAdapter();
}
}
So here inside of settingAdapter i reloaded data.
so far,it's the best trick i made toward fragments with recyclerviews inside viewpager. But still there are few milliseconds delay for populating fragment with new data)))
I hope this will help you

Passing Values to ViewPager Fragment

I want to pass dogruYanlis value which is an integer array to these fragments. If I try to handle this with bundle it it sends anything. The array that I received in fragment class is always null. I think that I can't handle with bundle but I don't know how I can solve this problem...
The Activity that I want to send data
package oztiryaki.my;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class result extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Bundle bundle;
int[] dogruYanlis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
toolbar = (Toolbar) findViewById(R.id.toolbarResult);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Bundle list = getIntent().getExtras();
if(list == null){
return;
}
dogruYanlis = list.getIntArray("dogruYanlis");
}
#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;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
bundle = new Bundle();
bundle.putIntArray("dogruYanlis", dogruYanlis);
result2015Fragment f15 = new result2015Fragment();
f15.setArguments(bundle);
result2014Fragment f14 = new result2014Fragment();
f14.setArguments(bundle);
result2013Fragment f13 = new result2013Fragment();
f13.setArguments(bundle);
adapter.addFragment(f15, "2015");
adapter.addFragment(f14, "2014");
adapter.addFragment(f13, "2013");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
The one of fragment activity
package oztiryaki.my;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by oztir on 21.02.2016.
*/
public class result2015Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.result2015,container,false);
int[] dogruYanlis = getArguments().getIntArray("dogruYanlis");
if(dogruYanlis == null){
Toast.makeText(getActivity(),"null sory:(", Toast.LENGTH_LONG).show();
}
TextView ygs1hp = (TextView) v.findViewById(R.id.ygs1hp);
return v;
}
public void getArray(int[] dogruYanlis){
Toast.makeText(getActivity(),Integer.toString(dogruYanlis[0]), Toast.LENGTH_LONG).show();
}
}
I had a similar struggle, maybe this will help. In case if your variables in the activity are not changing after it is created, there is one simple way to reach out to the activity's variables from the fragment it creates:
get the context in the fragment
then you can get the value of the variable from the fragment
Context context;
public void onViewCreated(View v, Bundle savedInstanceState) {
context = getActivity();
int i = ((result)context).dogruYanlis[0];
}
Try to create a Fragment using the wizard that Android studio provides, which gives you a dummy Fragment, with all the Fragment methods you need to pass data and such:
package FRAGMENTS;
import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentLifecycleDemo extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String TEXT1 = "text1";
private static final String TEXT2 = "text2";
// the two strings are going to be used here
private TextView title;
private TextView subtitle;
private String text1;
private String text2;
private Context c;
private OnFragmentInteractionListener mListener;
public FragmentLifecycleDemo(Context c) {
// Required empty public constructor
this.c = c;
}
public static FragmentLifecycleDemo newInstance(String title, String subtitle, Context c) {
FragmentLifecycleDemo fragment = new FragmentLifecycleDemo(c);
Bundle args = new Bundle();
args.putString(TEXT1, title);
args.putString(TEXT2, subtitle);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(c, "Hi! onCreate has just been called.", Toast.LENGTH_SHORT).show();
if (getArguments() != null) {
text1 = getArguments().getString(TEXT1);
text2 = getArguments().getString(TEXT2);
}
}
private void init(View v) {
title = (TextView) v.findViewById(R.id.txtTry);
title.setText(text1);
subtitle = (TextView) v.findViewById(R.id.txtReal);
subtitle.setText(text2);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lifecycle_demo, container, false);
init(v);
Toast.makeText(c, "Greetings from onCreateView!", Toast.LENGTH_SHORT).show();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Toast.makeText(c, "Is it me, or a button has just been pressed?", Toast.LENGTH_SHORT).show();
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Toast.makeText(c, "Howdy! I've just been attached to the activity.", Toast.LENGTH_SHORT).show();
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
Toast.makeText(c, "Oh no! I've been detached u.u", Toast.LENGTH_SHORT).show();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
As you can see, the method where you should get the Bundle is the onCreate one, that receives the data you want to be available on the Fragment, which was send from the constructor named newInstance.

Categories

Resources