Я перечислил все свои данные из базы данных MySQL в RecyclerView. В последнее время RecyclerView не может щелкать и отображать только весь список. Таким образом, я хочу знать код для перенаправления выбранного элемента в RecyclerView в другое действие. Например, в RecyclerView есть список «Заголовок 1, Заголовок 2, Заголовок 3». Когда я нажимаю «Заголовок 1», он перенаправляет на другой вид деятельности со всем содержимым из «Заголовка 1». Ниже мой код:
// Основная деятельность
private static final String URL_PRODUCTS = "http://10.0.2.2/listview/Api.php";
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the recyclerview from xml
recyclerView = findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
productList.add(new Product(
product.getInt("id"),
product.getString("title"),
product.getString("name"),
product.getString("time")
));
}
//creating adapter object and setting it to recyclerview
ProductsAdapter adapter = new ProductsAdapter(MainActivity.this, productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
// Адаптер продуктов
private Context mCtx;
private List<Product> productList;
public ProductsAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
@Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.product_list, null);
return new ProductViewHolder(view);
}
@Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Product product = productList.get(position);
holder.tvName.setText(product.getTitle());
holder.tvTitle.setText(product.getName());
holder.tvTime.setText(product.getTime());
}
@Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView tvName, tvTitle, tvTime;
public ProductViewHolder(View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tvName);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvTime = itemView.findViewById(R.id.tvTime);
}
}
// Продукт
public Product(int id, String title, String name, String time) {
this.id = id;
this.title = title;
this.name = name;
this.time = time;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getName() {
return name;
}
public String getTime() {
return time;
}
// PHP
//database constants
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'listview');
//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//creating a query
$stmt = $conn->prepare("SELECT id, title, name, time FROM products;");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($id, $title, $name, $time);
$products = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['id'] = $id;
$temp['title'] = $title;
$temp['name'] = $name;
$temp['time'] = $time;
array_push($products, $temp);
}
//displaying the result in json format
echo json_encode($products);