片段间通信onclick textview为null但在oncreate视图中textview就在那里

时间:2018-01-18 21:32:25

标签: java android android-fragments

  

您好,我尝试通过实现接口将数据从一个片段发送到另一个片段。 Communicator接口实现了两个函数,其中一个是sendToBill(itemType,itemPrice)。当在CategoryFragment类中单击添加按钮时,我希望将项目的价格添加到页脚片段中的金额。单击添加按钮时得到的错误是页脚片段中的textview为null。   在FooterFragment类中是一个函数updateBill()。当从onActivityCreated调用此函数时(在footerFragment类中),视图存在。

FooterBillFragment:

BillFragment extends android.support.v4.app.Fragment {

    private TextView totalAmount, text;
    private View mView;

    public FooterBillFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_footer_bill, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        totalAmount = (TextView) getView().findViewById(R.id.footer_display_amount);
        text = getView().findViewById(R.id.footer_bill_text);
        Log.d("ItemPrice", "item View footer " + text.getText().toString());
    }

    public void testTest() {
        totalAmount.setText("dit werkt wel");
    }

    public void updateFooterAmount(String itemPrice) {
        Log.d("ItemPrice", "item price footer " + itemPrice);
        totalAmount.setText("On click in CategorieFragment this TextView does 
        not exist"); This is where the error occurs
    }
}

我的活动:

public class IntermediateActivity extends AppCompatActivity implements Communicator {

    private static int count = 0;
    private DatabaseReference mMenuCardDatabase;
    private FirebaseUser mCurrentUser;

    private ViewPager mPager;
    private MyFragmentPageAdapter mPageAdapter;
    private TabLayout mTabLayout;

    private ArrayList<String> categories;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intermediate);

        categories = new ArrayList<>();
        String shop_id = getIntent().getStringExtra("shop_id");

        mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

        mMenuCardDatabase = FirebaseDatabase.getInstance().getReference().child("MenuCard").child(shop_id);
        mMenuCardDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    categories.add(ds.getKey().toString());
                }
                List<Fragment> fragments = buildFragments(categories.size());
                mPager = (ViewPager) findViewById(R.id.intermediate_tabPager);

                mPageAdapter = new MyFragmentPageAdapter(IntermediateActivity.this, getSupportFragmentManager(), fragments, categories);
                mPager.setAdapter(mPageAdapter);
                mTabLayout = (TabLayout) findViewById(R.id.intermediate_tabs);

                mTabLayout.setupWithViewPager(mPager);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    public String getUserId() {
        String user_id = getIntent().getStringExtra("user_id");

        return user_id;
    }

    private List<android.support.v4.app.Fragment> buildFragments(int categoriesSize) {
        List<Fragment> fragments = new ArrayList<Fragment>();
        for(int i = 0; i < categoriesSize; i++) {
            Bundle b = new Bundle();
            b.putInt("position", i);
            String categorie = categories.get(i);

            b.putString("categorie", categorie);
            fragments.add(Fragment.instantiate(this, CategoryFragment.class.getName() , b));
        }

        return fragments;
    }

    @Override
    public void respond(String shopType) {

    }

    @Override
    public void sendToBill(String itemName, String itemPrice) {
        count++;
        FooterBillFragment footerBillFragment = new FooterBillFragment();

        BillFragment billFragment = new BillFragment();
        billFragment.updateBill(itemName, itemPrice);

        Log.d("ItemPrice", "item price inter " + itemPrice);
        footerBillFragment.updateFooterAmount(itemPrice);
    }
}

CategoryFragment:

public class CategoryFragment extends android.support.v4.app.Fragment {

    private DatabaseReference mMenuCardDatabase;
    private DatabaseReference mUserDatabase;
    private FirebaseUser mCurrentUser;

    private RecyclerView mItemsList;
    private Communicator comm;


    public CategoryFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View mView = inflater.inflate(R.layout.fragment_category, container, false);

        String categorie = this.getArguments().getString("categorie");


        mItemsList = (RecyclerView) mView.findViewById(R.id.items_guests_list);

        mItemsList.setLayoutManager(new LinearLayoutManager(getContext()));
        mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
        mMenuCardDatabase = FirebaseDatabase.getInstance().getReference().child("MenuCard").child(mCurrentUser.getUid()).child(categorie);

        return mView;
    }

    @Override
    public void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Items, ItemsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Items, CategoryFragment.ItemsViewHolder>(
                Items.class,
                R.layout.single_menu_display_layout,
                ItemsViewHolder.class,
                mMenuCardDatabase
        ) {
   @Override
    protected void populateViewHolder(CategoryFragment.ItemsViewHolder 
           viewHolder, Items item, int position) {

                comm = (Communicator) getActivity();

                String itemName = item.getItemName();
                String itemPrice = item.getItemPrice();
                viewHolder.setItemName(itemName);
                viewHolder.setItemPrice(itemPrice);
                viewHolder.setItemAddBtn(itemName, itemPrice, comm);

            }
        };

        mItemsList.setAdapter(firebaseRecyclerAdapter);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    public static class ItemsViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public ItemsViewHolder(View itemView) {
            super(itemView);

            mView = itemView;
        }

        public void setItemName(String name) {
            TextView mUser_name_view = (TextView) mView.findViewById(R.id.item_display_single_name);
            mUser_name_view.setText(name);

        }

        public void setItemPrice(String price) {
            TextView mItem_price_view = (TextView) mView.findViewById(R.id.item_display_single_price);
            mItem_price_view.setText(price);

        }

        public void setImage(String image, Context context) {
            CircleImageView mItem_image_view = (CircleImageView) mView.findViewById(R.id.item_display_single_image);

            Picasso.with(context).load(image).placeholder(R.drawable.placeholder_profilepic).into(mItem_image_view);

        }

        public void setItemAddBtn(final String itemName, final String itemPrice, final Communicator comm) {
            Button btn = (Button) mView.findViewById(R.id.item_display_single_add_btn);

            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    comm.sendToBill(itemName, itemPrice);
                    Log.d("ItemPrice", "item price adapter " + itemPrice);
                }
            });
        }
    }
}

2 个答案:

答案 0 :(得分:0)

if stringWithDiaeresis.localizedStandardContains(searchStringWithoutDiaeresis) {
  print("Reënter contains Ree")
}

/* Prints the following:
 Reënter contains Ree
 */

在“活动”中创建,您的片段视图为空,因为您的片段未创建。在onActivityCreated() 中使用TextView的方法。

答案 1 :(得分:0)

您正在此处创建片段的新实例,但它们未添加到活动中:

@Override
public void sendToBill(String itemName, String itemPrice) {
    count++;
    FooterBillFragment footerBillFragment = new FooterBillFragment();

    BillFragment billFragment = new BillFragment();
    billFragment.updateBill(itemName, itemPrice);

    Log.d("ItemPrice", "item price inter " + itemPrice);
    footerBillFragment.updateFooterAmount(itemPrice);
}

这就是你收到NullPointer的原因,因为onActivityCreated

永远不会调用方法FooterBillFragment