Как передать ссылку из RecyclerView в другой вид деятельности - PullRequest
0 голосов
/ 30 декабря 2018

У меня проблема с моим кодом.Мне нужно передать ссылку из RecylerViewAdapter.java в DrinkActivity.java.Когда я нажимал на элемент в RecyclerView, он должен был передать позицию в DrinkActivity, чтобы я мог отобразить имя и цену.У меня нет проблем при отображении имени, цены и изображения в Home.java.Но я не знаю, что происходит, когда я запускаю его, я получил исключение нулевого указателя на DrinkActivity.

Спасибо.

Это скриншот моего рециркулятора

Это скриншот после нажатия на элемент

Это мой RecylerViewAdapter.java

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.myViewHolder> {

private Context mContext;
private List<Drink> mData;

RequestOptions option;

public RecyclerViewAdapter(Context mContext, List<Drink> mData) {
    this.mContext = mContext;
    this.mData = mData;

    //Request option for Glide
    option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}

@Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.drink_item, parent, false);

    final myViewHolder viewHolder = new myViewHolder(view);

    viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(mContext, DrinkActivity.class);
            i.putExtra("name", mData.get(viewHolder.getAdapterPosition()).getName());
            i.putExtra("price", mData.get(viewHolder.getAdapterPosition()).getPrice());
            i.putExtra("img", mData.get(viewHolder.getAdapterPosition()).getImage_url());

            mContext.startActivity(i);
        }
    });

    return viewHolder;
}

@Override
public void onBindViewHolder(myViewHolder myViewHolder, int position) {
    myViewHolder.drink_name.setText(mData.get(position).getName());
    myViewHolder.drink_price.setText(String.valueOf(mData.get(position).getPrice()));

    Glide.with(mContext).load(mData.get(position).getImage_url()).apply(option).into(myViewHolder.img_thumbnail);
}

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public static class myViewHolder extends RecyclerView.ViewHolder {

        TextView drink_name;
        TextView drink_price;
        ImageView img_thumbnail;

        LinearLayout item_drink;
        LinearLayout view_container;

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

            view_container = (LinearLayout) itemView.findViewById(R.id.container);

            item_drink = (LinearLayout) itemView.findViewById(R.id.drink_item_id);

            drink_name = itemView.findViewById(R.id.name);
            drink_price = itemView.findViewById(R.id.price);
            img_thumbnail = itemView.findViewById(R.id.thumbnail);
        }
    }    
}

Это Home.java

public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private RecyclerView recycler_menu;
private RecyclerView.LayoutManager layoutManager;

private List<Drink> drinkList = new ArrayList<>();

DatabaseReference dbDrink;

Dialog myDialog;
TextView titleTv, priceTv;

public Home(){

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Customer");
    setSupportActionBar(toolbar);

    myDialog = new Dialog(this);

    dbDrink = FirebaseDatabase.getInstance().getReference().child("Drink");

    final FirebaseDatabase database = FirebaseDatabase.getInstance();

    //Load drink
    recycler_menu = (RecyclerView) findViewById(R.id.recyclerview_id);
    recycler_menu.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recycler_menu.setLayoutManager(layoutManager);

    loadDrink();

    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.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


}

private void loadDrink() {
    FirebaseRecyclerAdapter<Drink, DrinkViewHolder> adapter = new FirebaseRecyclerAdapter<Drink, DrinkViewHolder>(Drink.class, R.layout.drink_item, DrinkViewHolder.class, dbDrink) {

        @Override
        protected void populateViewHolder(DrinkViewHolder viewHolder, final Drink model, int position) {

            viewHolder.txtDrinkName.setText(model.getName());
            viewHolder.txtPrice.setText(String.valueOf(model.getPrice()));

            Picasso.get().load(model.getImage_url())
                    .into(viewHolder.imageView);
            final Drink clickItem = model;

            viewHolder.setItemClickListener(new ItemClickListener() {

                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                    Toast.makeText(Home.this, "" + clickItem.getName(), Toast.LENGTH_SHORT).show();

                    Intent main =  new Intent(Home.this, DrinkActivity.class);
                    main.putExtra("name", model.getName());
                    main.putExtra("price", model.getPrice());
                    main.putExtra("img", model.getImage_url());
                    startActivity(main);
                }
            });
        }
    };
    recycler_menu.setAdapter(adapter);
}

@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.home, 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);
}

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_menu) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Это DrinkActivity.java

    public class DrinkActivity extends AppCompatActivity {

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

        TextView tv_name = (TextView) findViewById(R.id.name);
        TextView tv_price = (TextView) findViewById(R.id.price);

        String name = getIntent().getExtras().getString("name");
        double price = getIntent().getExtras().getDouble("price");

        tv_name.setText(name);
        tv_price.setText(String.valueOf(price));

        }    
    }

1 Ответ

0 голосов
/ 30 декабря 2018

В onClick вашего адаптера вы запускаете DrinkActivity без передачи каких-либо данных:

Intent main =  new Intent(Home.this, DrinkActivity.class);
startActivity(main);

Вам также необходимо передать имя и цену, т.е.

Intent main =  new Intent(Home.this, DrinkActivity.class);
main.putExtra("name", model.getName());
main.putExtra("price", model.getPrice());
startActivity(main);
...