Hello I am newbie in java programming(android). Currently I learn recyclerview use volley in fragments and need help. why when switching fragment one to fragment two and when back to fragment one, recycleview lost? even though at the beginning recyleview available? thanks for help
this is backgroundtask.java
Context mContext;
ArrayList<List> mArrayList = new ArrayList<>();
String json_url = "http://192.168.43.215/belajar/contact_mad.php";
private static final String TAG = "BackgroundTask";
public BackgroundTask(Context context) {
this.mContext = context;
}
public ArrayList<List> getList()
{
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, (String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count<response.length())
{
try {
JSONObject jsonObject = response.getJSONObject(count);
List list = new List(jsonObject.getString("Id"),jsonObject.getString("ImageUrl"),jsonObject.getString("Name"));
mArrayList.add(list);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext,"Errorr.............",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}
);
MySingleton.getInstance(mContext).addToRequestQue(jsonArrayRequest);
Log.e(TAG, "Log Dari background");
return mArrayList;
}
this is recycleradapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<List> mArrayList = new ArrayList<>();
private static final String TAG = "RecyclerAdapter";
public RecyclerAdapter(ArrayList<List> arrayList){
this.mArrayList = arrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final String name = mTxtName.getText().toString();
final String email = mTxtEmail.getText().toString();
final String nameFood = this.mArrayList.get(position).getName();
final String imageUrl = this.mArrayList.get(position).getImageUrl();
holder.Name.setText(mArrayList.get(position).getName());
final Context context = holder.mImageView.getContext();
Picasso.with(context).load(mArrayList.get(position).getImageUrl()).into(holder.mImageView);
Log.e(TAG, "Log Dari On BindView");
holder.cvMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Intent intent = new Intent(v.getContext(),ActivityClick.class);
Bundle bundle = new Bundle();
bundle.putString("imageUrl",imageUrl);
bundle.putString("name",name);
intent.putExtras(bundle);
v.getContext().startActivity(intent);*/
Toast.makeText(context, name, Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return mArrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView Name;
RelativeLayout cvMain;
ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView);
Name = (TextView)itemView.findViewById(R.id.txtName);
cvMain = (RelativeLayout) itemView.findViewById(R.id.cvMain);
}
}
this is MainMenu.java
public class MainMenu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static TextView mTxtName, mTxtEmail;
private Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mTxtName = (TextView)navigationView.getHeaderView(0).findViewById(R.id.txtNavName);
mTxtEmail = (TextView)navigationView.getHeaderView(0).findViewById(R.id.txtNavEmail);
Bundle bundle = getIntent().getExtras();
mTxtName.setText(bundle.getString("name"));
mTxtEmail.setText(bundle.getString("email"));
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.tempatfragment, new ListMakanan()).addToBackStack(null).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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, 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.cara_pesan) {
return true;
}else if(id == R.id.keluar){
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fm.beginTransaction();
if (id == R.id.list_makanan) {
transaction.replace(R.id.tempatfragment, new ListMakanan()).addToBackStack(null).commit();
} else if (id == R.id.pesan_makanan) {
transaction.replace(R.id.tempatfragment, new PesanMakanan()).addToBackStack(null).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
this is fragment ListMakanan.java
public class ListMakanan extends Fragment {
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
ArrayList<List> mArrayList = new ArrayList<>();
private static final String TAG = "ListMakanan";
public ListMakanan() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list__makanan, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView)view.findViewById(R.id.recyclervView);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
BackgroundTask backgroundTask = new BackgroundTask(getActivity());
mArrayList = backgroundTask.getList();
mAdapter = new RecyclerAdapter(mArrayList);
mRecyclerView.setAdapter(mAdapter);
Log.e(TAG, "Log Dari View Created");
}
Whenever you use replace on your FragmentManager to switch fragments you are doing a remove(remove any fragments from container) followed by an add(the new fragment). This wipes out the state of the previous fragment and forces a refresh when you go back, to avoid this you can just call add fragment instead of replace.
Related
I am trying to implement a sales app with 3 stages, whereby a user first adds the items, views the cart to checkout and prints a receipt. The first stage is done and works well. I am implementing this using one Activity with a tabbed layout and 3 fragments for each of the tabs.
On the activity for viewing the cart, I am using a RecyclerView which loads well when the activity is created, but once I add an item and try to view the list, there is no update. However, when I print the item list, the item has been added.
I have tried to update the RecyclerView using notifyDataSetChanged() but it gives me a null pointer exception. I have and tried several solutions but none has worked. Kindly assist.
Below is my code.
NewSaleActivity.java
public class NewSaleActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private ActivityNewSaleBinding binding;
DrawerLayout drawerLayout;
NavigationView navigationView;
TabLayout tabLayout;
Context context;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityNewSaleBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Toolbar toolbar = findViewById(R.id.new_sale_toolbar);
toolbar.setTitle(R.string.new_sale);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.new_sale_drawer);
navigationView = findViewById(R.id.new_sale_navigation);
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_sale);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
context = getApplicationContext();
tabLayout = findViewById(R.id.tab_layout);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
viewPager = binding.viewPager;
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOffscreenPageLimit(1);
TabLayout tabs = binding.tabLayout;
tabs.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//When cart tab is selected
if(tab.getPosition() == 1) {
CartFragment cartFragment = new CartFragment();
cartFragment.loadItemsInCart();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
Intent mainIntent = new Intent(NewSaleActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
break;
case R.id.nav_inventory:
Intent inventoryIntent = new Intent(NewSaleActivity.this, InventoryActivity.class);
startActivity(inventoryIntent);
finish();
break;
case R.id.nav_sale:
break;
case R.id.nav_logout:
UserLogout.userLogout(NewSaleActivity.this);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
CartFragment.java
public class CartFragment extends Fragment {
RecyclerView cartRecyclerView;
TextInputLayout grossTotalInput, discountInput, netTotalInput;
Button checkoutButton;
CartItemAdapter cartItemAdapter;
ArrayList<CartItem> cartItemList;
public CartFragment() {
// Required empty public constructor
}
public static CartFragment newInstance() {
CartFragment fragment = new CartFragment();
Bundle args = new Bundle();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
cartRecyclerView = view.findViewById(R.id.cart_recycler_view);
grossTotalInput = view.findViewById(R.id.gross_total_input);
discountInput = view.findViewById(R.id.discount_input);
netTotalInput = view.findViewById(R.id.net_total_input);
checkoutButton = view.findViewById(R.id.checkout_button);
Paper.init(requireContext());
cartItemList = Paper.book().read("cartItems", new ArrayList<CartItem>());
cartRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
cartItemAdapter = new CartItemAdapter(cartItemList);
cartRecyclerView.setAdapter(cartItemAdapter);
checkoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkoutOrder();
}
});
cartItemAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_cart, container, false);
}
public void loadItemsInCart() {
ArrayList<CartItem> cartList = Paper.book().read("cartItems", new ArrayList<CartItem>());
for(CartItem cartItem : cartList) {
Log.d("cartItem", cartItem.getItemName());
}
cartItemAdapter.updateCartList(cartList);
Log.d("loadItemsInCart", "Load Items In Cart is triggered");
}
CartItemAdapter.java
public class CartItemAdapter extends RecyclerView.Adapter<CartItemAdapter.ViewHolder> {
private final ArrayList<CartItem> cartItems;
public CartItemAdapter(ArrayList<CartItem> cartItems) {
this.cartItems = cartItems;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView itemCode, itemName, quantity, price;
public ViewHolder(View itemView) {
super(itemView);
this.itemCode = itemView.findViewById(R.id.item_code);
this.itemName = itemView.findViewById(R.id.item_name);
this.quantity = itemView.findViewById(R.id.item_quantity);
this.price = itemView.findViewById(R.id.item_price);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View cartListItem = layoutInflater.inflate(R.layout.add_to_cart_item, parent, false);
return new CartItemAdapter.ViewHolder(cartListItem);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.itemCode.setText(cartItems.get(position).getItemCode());
holder.itemName.setText(cartItems.get(position).getItemName());
holder.quantity.setText(cartItems.get(position).getQuantity().toString());
holder.price.setText(cartItems.get(position).getTotalAmount().toString());
}
#Override
public int getItemCount() {
return cartItems.size();
}
#SuppressLint("NotifyDataSetChanged")
public void updateCartList(ArrayList<CartItem> cartList) {
cartItems.clear();
this.cartItems.addAll(cartList);
notifyDataSetChanged();
}
}
The error message that I get is as below
java.lang.NullPointerException: Attempt to invoke virtual method 'void app.project.jsml_sales_app.adapters.CartItemAdapter.updateCartList(java.util.ArrayList)' on a null object reference
at app.project.jsml_sales_app.activities.fragments.CartFragment.loadItemsInCart(CartFragment.java:128)
at app.project.jsml_sales_app.activities.NewSaleActivity$1.onTabSelected(NewSaleActivity.java:78)
at com.google.android.material.tabs.TabLayout.dispatchTabSelected(TabLayout.java:1993)
at com.google.android.material.tabs.TabLayout.selectTab(TabLayout.java:1986)
I am using DrawerLayoutmenu with a ViewPager and recycleView in my application and I have three tabs in it. I am using ViewPager and recycleView inside a fragment. Now my problem here is, the first time there is no error and when i come back fragment CongThucFragment It looks like it was error
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SharedPreferences sharedPreferencesToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferencesToken=getSharedPreferences("DataChefy",Context.MODE_PRIVATE);
TokenClass.Token = sharedPreferencesToken.getString("Token","");
Log.d("MainActivity10",TokenClass.Token);
if (savedInstanceState == null) {
Fragment fragment = null;
Class fragmentClass = null;
fragmentClass = UserInfoFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
int id = item.getItemId();
Class fragmentClass = null;
if (id == R.id.nav_camera) {
fragmentClass = UserInfoFragment.class;
try {
ft.replace(R.id.fragment_container,(Fragment) fragmentClass.newInstance(), "UserInfoFragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
fragmentClass = CongThucFragment.class;
try {
ft.replace(R.id.fragment_container,(Fragment) fragmentClass.newInstance(), "CongThucFragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else if (id == R.id.nav_manage) {
SharedPreferences.Editor editor = sharedPreferencesToken.edit();
editor.putString("Token","");
editor.apply();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
this.finish();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}}
and this my fragment
public class CongThucFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private FragmentActivity myContext;
static public CongThucFragment newInstance(){
return new CongThucFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
myContext = (FragmentActivity) context;
setRetainInstance(true);
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmen_congthuc,container,false);
tabLayout= (TabLayout) view.findViewById(R.id.tabsChampionDetail);
viewPager= (ViewPager) view.findViewById(R.id.viewpagerChampionDetail);
tabLayout.setupWithViewPager(viewPager);
setupViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager ) {
ViewPagerAdapter adapter = new ViewPagerAdapter(myContext.getSupportFragmentManager());
for(int i =1 ;i<=3.;i++) {
if(i==1)adapter.addFragment(ChildrenCongthucFragment.newInstance("vn"), "Country " + i + "");
else if(i==2)adapter.addFragment(ChildrenCongthucFragment.newInstance("lao"), "Country " + i + "");
else adapter.addFragment(ChildrenCongthucFragment.newInstance("tay"), "Country " + i + "");
}
viewPager.setAdapter(adapter);
}}
fragment 2
public class ChildrenCongthucFragment extends Fragment{
String Country = null;
List<Congthuc> mItems = new ArrayList<>();
private RecyclerView mRecyclerView;
private RecyclerDataAdapter recyclerDataAdapter = null;
RecyclerView.LayoutManager layoutManagerNews;
static public ChildrenCongthucFragment newInstance(String country){
Bundle bundle = new Bundle();
bundle.putString("mCountry",country);
ChildrenCongthucFragment fragment = new ChildrenCongthucFragment();
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeData();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycle_children_congthuc,container,false);
Country = getArguments().getString("mCountry");
mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_photo_collection_recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
recyclerDataAdapter =new RecyclerDataAdapter (view.getContext(),R.layout.recycle_children_congthuc,CountryFillter(Country,mItems));
mRecyclerView.setAdapter(recyclerDataAdapter);
return view;
}
private void initializeData(){
mItems.add(new Congthuc("1", "banh mì","vn","http://giadinh.vcmedia.vn/k:2016/photo-0-1472785146823/nhungmonanngonchogiadinhdip29.jpg"));
mItems.add(new Congthuc("2", "bánh gián","vn","http://toinayangi.vn/wp-content/uploads/2015/06/m%C3%B3n-%C4%83n-vi%E1%BB%87t-nam-n%E1%BB%95i-ti%E1%BA%BFng-g%E1%BB%8Fi-cu%E1%BB%91n.jpg"));
mItems.add(new Congthuc("3", "bún","lao", "http://anh.eva.vn/upload/2-2016/images/2016-06-12/5-mon-an-ngon-tuyet-cho-cuoi-tuan-5-1465696055-width640height80.jpg"));
mItems.add(new Congthuc("4", "phỏ", "lao","https://i0.wp.com/theboola.com/wp-content/uploads/2014/09/144837125.jpg?resize=506%2C341"));
mItems.add(new Congthuc("5", "hủ tíu","tay", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_AWhsxDkMDqkIhPGSNLZj8TFAkF3pedEa6Tt-l72mSt6PdRXaEg"));
mItems.add(new Congthuc("6", "cam","tay", "https://i.imgur.com/3M37NQM.jpg"));
mItems.add(new Congthuc("7", "quýt","ta", "http://vnngon.com/wp-content/uploads/2016/01/cach-lam-mon-an-ngon-ga-nhoi-thap-cam-xoi-vnngon-2.jpg"));
}ArrayList<Congthuc> CountryFillter(String con,List<Congthuc> cts){
List<Congthuc> Ncts = new ArrayList<>();
for (int i = 0;i<cts.size();i++)
{
Congthuc ct = cts.get(i);
if (con.equals(ct.getQuocGia()))
{
Ncts.add(ct);
}
}
return (ArrayList<Congthuc>) Ncts;}}
my adapter
public class RecyclerDataAdapter extends RecyclerView.Adapter<RecyclerDataAdapter.ViewHolder> {
private List<Congthuc> congthucs;
private int layout;
private Context context;
public RecyclerDataAdapter(Context context, int layout, List<Congthuc> congthucs) {
this.context = context;
this.layout=layout;
this.congthucs = congthucs;
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imgCT;
TextView txtCT;
public ViewHolder(View itemView) {
super(itemView);
imgCT= (ImageView) itemView.findViewById(R.id.fragment_image_View);
txtCT= (TextView) itemView.findViewById(R.id.txtDes);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_collection, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Congthuc congthuc = congthucs.get(position);
holder.txtCT.setText(congthuc.getDescription());
Picasso.with(context)
.load(congthuc.getLink())
.placeholder(R.drawable.loader)
.error(R.drawable.placeholder)
.resize(150,120)
.centerCrop()
.skipMemoryCache()
.into(holder.imgCT);
}
#Override
public int getItemCount() {
return congthucs ==null?0:congthucs.size();
}}
I have problem when I cast the context in the FragmentAdapter of a Fragment. My app process is:
- When I click on navigation list item (Nav One) it will show the fragment with the recyclerview and cardview.
- When I click on the image of cardview list item I want get an action to show the Toast message or do something with a costom interface named (CustomCallBack).
This is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListView lvNavigation;
private DrawerLayout mDrawer;
private NavigationView mNavigation;
private LinearLayout llMianContain;
String[] navigation = new String[]{"Nav One","Nav Two", "Nav Three","Nav Four"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
lvNavigation = (ListView) findViewById(R.id.lv_listView);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigation= (NavigationView) findViewById(R.id.navigation_view);
llMianContain = (LinearLayout) findViewById(R.id.ll_main_content);
setSupportActionBar(toolbar);
lvNavigation.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, navigation));
lvNavigation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
replaceFragment(i);
lvNavigation.setItemChecked(i, true);
hideDrawer();
}
});
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.open, R.string.close);
mDrawer.setDrawerListener(toggle);
toggle.syncState();
}
private void replaceFragment(int position){
Fragment fragment = null;
switch (position){
case 0:
fragment = new OneFragment();
break;
case 1:
fragment = new TwoFragment();
break;
case 2:
fragment = new ThreeFragment();
break;
case 3:
fragment= new FourFragment();
break;
default:
fragment = new OneFragment();
break;
}
if(null!= fragment){
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.ll_main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
private void hideDrawer(){
mDrawer.closeDrawer(GravityCompat.START);
}
private void showDrawer(){
mDrawer.openDrawer(GravityCompat.START);
}
#Override
public void onBackPressed() {
if (mDrawer.isDrawerOpen(GravityCompat.START))
hideDrawer();
else
super.onBackPressed();
}
}
OneFragment.java
public class OneFragment extends Fragment implements FragmentOneAdapter.CustomCallBack{
private ArrayList<ListItem> listItems;
private RecyclerView recyclerView;
private FragmentOneAdapter adapter;
public OneFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_one, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
LinearLayoutManager manager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(manager);
listItems = new ArrayList<>();
for(int i=0;i<40;i++){
listItems.add(new ListItem(R.drawable.ic_account_circle_black_48dp, "MY NAME "+ i));
}
adapter = new FragmentOneAdapter(listItems, getActivity());
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onProfileClick(int position) {
Toast.makeText(getActivity(), "position "+ position, Toast.LENGTH_SHORT).show();
}
}
FragmentAdapter.java
public class FragmentOneAdapter extends RecyclerView.Adapter<FragmentOneAdapter.FragmentOneViewHolder> {
private ArrayList<ListItem> listItems;
private Context context;
final CustomCallBack customCallBack;
public FragmentOneAdapter(ArrayList<ListItem> listItems, Context context){
this.listItems = listItems;
this.context = context;
this.customCallBack = (CustomCallBack) context;
}
#Override
public FragmentOneViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_one_item, parent,false);
FragmentOneViewHolder holder = new FragmentOneViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(FragmentOneViewHolder holder, int position) {
holder.tvName.setText(listItems.get(position).getName());
holder.ivProfile.setImageResource(listItems.get(position).getProfile());
}
#Override
public int getItemCount() {
return listItems.size();
}
class FragmentOneViewHolder extends RecyclerView.ViewHolder{
TextView tvName;
ImageView ivProfile;
LinearLayout llFooter;
public FragmentOneViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tv_name);
ivProfile = (ImageView) itemView.findViewById(R.id.iv_profile);
llFooter= (LinearLayout) itemView.findViewById(R.id.ll_footer);
ivProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
customCallBack.onProfileClick(getAdapterPosition());
}
});
}
}
// MY Custom CallBack
interface CustomCallBack{
void onProfileClick(int position);
}
}
Hmm,
So your Fragment is implementing CustomCallBack interface
Why don't you just pass the Fragment object itself to the adapter?
for example, in the FragmentOneAdapter.java,
change:
public FragmentOneAdapter(ArrayList<ListItem> listItems, Context context) ===> public FragmentOneAdapter(ArrayList<ListItem> listItems, CustomCallBack callback)
then:
this.customCallBack = (CustomCallBack) context; ===> this.customCallBack = callback;
Obviously, now in OneFragment.java,
just pass 'this' as parameter as the Fragment itself is the CustomCallBack:
adapter = new FragmentOneAdapter(listItems, getActivity()); ===> adapter = new FragmentOneAdapter(listItems, this);
The mainactivity contains navigation drawer. When I click on the navigation drawer tabs, the respective fragment will be opened and in that fragment in Homefragment I want to add ViewPager.
I have added ViewPager in HomeFragment but it is not scrolling horizontally.
This is mainActivity:
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private Toolbar toolbar;
private FloatingActionButton fab;
public static int navItemIndex = 0;
private static final String TAG_HOME = "home";
private static final String TAG_PHOTOS = "photos";
private static final String TAG_MOVIES = "movies";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_bar_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
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();
}
});
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
private void loadNavHeader() {
// showing dot next to notifications label
navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
toggleFab();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
// show or hide the fab button
toggleFab();
drawer.closeDrawers();
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
case 2:
MoviesFragment moviesFragment = new MoviesFragment();
return moviesFragment;
case 3:
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 4:
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_service_message:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_privacy_policy:
startActivity(new Intent(MainActivity.this, PrivacyPolicyActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
if (shouldLoadHomeFragOnBackPress) {
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
if (navItemIndex == 3) {
getMenuInflater().inflate(R.menu.notifications, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}
This is HomeFragment:
public class HomeFragment extends Fragment {
public HomeFragment() {
}
View view;
ViewPager viewPager;
PagerAdapter adapter;
String[] rank;
String[] country;
String[] population;
int[] flag;
public PageIndicator mIndicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);
rank = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
country = new String[] { "China", "India", "United States",
"Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh",
"Russia", "Japan" };
population = new String[] { "1,354,040,000", "1,210,193,422",
"315,761,000", "237,641,326", "193,946,886", "182,912,000",
"170,901,000", "152,518,015", "143,369,806", "127,360,000" };
flag = new int[] { R.drawable.china, R.drawable.india,
R.drawable.unitedstates, R.drawable.indonesia,
R.drawable.brazil, R.drawable.pakistan, R.drawable.nigeria,
R.drawable.bangladesh, R.drawable.russia, R.drawable.japan };
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mIndicator = (PageIndicator) view.findViewById(R.id.pagerIndicator);
viewPager = (ViewPager) view.findViewById(R.id.pager);
adapter = new ViewPagerAdapter(getActivity(), rank, country, population, flag);
viewPager.setAdapter(adapter);
mIndicator.setViewPager(viewPager);
}
}
This is adapter-
public class ViewPagerAdapter extends PagerAdapter {
Context context;
String[] rank;
String[] country;
String[] population;
int[] flag;
LayoutInflater inflater;
public ViewPagerAdapter(Context context, String[] rank, String[] country,
String[] population, int[] flag) {
this.context = context;
this.rank = rank;
this.country = country;
this.population = population;
this.flag = flag;
}
#Override
public int getCount() {
return rank.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
ImageView imgflag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
txtrank = (TextView) itemView.findViewById(R.id.rank);
txtcountry = (TextView) itemView.findViewById(R.id.country);
txtpopulation = (TextView) itemView.findViewById(R.id.population);
txtrank.setText(rank[position]);
txtcountry.setText(country[position]);
txtpopulation.setText(population[position]);
// Locate the ImageView in viewpager_item.xml
imgflag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set to the ImageView
imgflag.setImageResource(flag[position]);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
I have really browsed through stackoverflow for this solution.
Im trying to access a fragment from another fragment and an error is thrown that
java.lang.ClassCastException: com.noel.myapplication99.IncomeTax cannot be cast to com.noel.myapplication99.IncomeDialog
at com.noel.myapplication99.MainActivity.createOutput(MainActivity.java:119)
at com.noel.myapplication99.IncomeTax$1.onClick(IncomeTax.java:77)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19869)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
These are my codes
MainActivity.java
public class MainActivity extends AppCompatActivity
implements IncomeTax.OnFragmentInteractionListener, ResidentialIncomeTax.OnFragmentInteractionListener, NavigationDrawerFragment.NavigationDrawerCallbacks, IncomeTax.IncomeTaxListener {
public void onFragmentInteraction(Uri uri){
}
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment=null;
switch(position)
{
case 0:
fragment = new IncomeTax();
mTitle = getString(R.string.title_section1);
break;
case 1:
fragment = new ResidentialIncomeTax();
mTitle = getString(R.string.title_section2);
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment, "Tag").commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void createOutput(int i, int f) {
IncomeDialog incomeDialog = (IncomeDialog) getSupportFragmentManager().findFragmentByTag("Tag");
incomeDialog.setOutputText(i, f);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
IncomeTax.java
public class IncomeTax extends Fragment implements AdapterView.OnItemSelectedListener {
IncomeTaxListener activityCommander;
float selectedIncomeType;
public interface IncomeTaxListener{
public void createOutput(int i, int f);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (IncomeTaxListener) context;
}catch(Exception e){
throw new ClassCastException(toString());
}
}
private OnFragmentInteractionListener mListener;
public IncomeTax() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
Button btnIcCalc;
EditText salary, insuaranceRelief;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_tax, container, false);
salary = (EditText) view.findViewById(R.id.tvSalary);
insuaranceRelief = (EditText) view.findViewById(R.id.tvReliefCalc);
btnIcCalc = (Button)view.findViewById(R.id.btnIcCalc);
final int iSalary=0;
final int iInsuranceRelief=1;
btnIcCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Dialog box here
activityCommander.createOutput(iSalary, iInsuranceRelief);
FragmentManager manager = getActivity().getSupportFragmentManager();
IncomeDialog myDialog = new IncomeDialog();
myDialog.setTargetFragment(IncomeTax.this, 0);
myDialog.show(manager, "IncomeDialog");
}
});
setSpinnerContent(view);
return view;
}
private void setSpinnerContent( View view )
{
Spinner spinner = (Spinner) view.findViewById( R.id.incomeTypeSpinner );
ArrayAdapter incomeSpinnerArrayAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.income_type_array, android.R.layout.simple_spinner_item);
spinner.setAdapter(incomeSpinnerArrayAdapter );
spinner.setOnItemSelectedListener(this);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
selectedIncomeType = 1;
break;
case 1:
selectedIncomeType = 1;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
IncomeDialog.java
public class IncomeDialog extends DialogFragment {
public IncomeDialog() {
// Required empty public constructor
}
TextView netPay, insuranceRelief;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_dialog, null);
netPay = (TextView) view.findViewById(R.id.tvNetPay);
insuranceRelief = (TextView) view.findViewById(R.id.tvPersonalRelief);
return view;
}
public void setOutputText(int i, int f){
netPay.setText(i);
insuranceRelief.setText(f);
}
If you want to send data to DialogFragmet then try like this:
Bundle bundle = new Bundle();
bundle.putInt("key1", i);
bundle.putInt("key2", f);
IncomeDialog incomeDialog = new IncomeDialog();
incomeDialog.setArguments(bundle);
Now carry out FragmentTransaction to add this incomeDialog. That will show the dialog.
To receive the bundle data in IncomeDialog:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_dialog, null);
netPay = (TextView) view.findViewById(R.id.tvNetPay);
insuranceRelief = (TextView) view.findViewById(R.id.tvPersonalRelief);
Bundle bundle=getArguments();
int i = bundle.getInt("key1");
int f = bundle.getInt("key2");
return view;
}